Home > Net >  getting hours and minutes from input type of time
getting hours and minutes from input type of time

Time:09-21

Any suggestions on how to get the hours and minutes individually from this format 'hh:mm' using JavaScript?

<input type="time" id="timepicker" onchange="timePassed(this.value)">

<script>
    function timePassed(time) {
        var hours;
        var mins;
        //todo: get the hours and minutes from the input value and store them in separate variables
    }
</script>

I tried using getHours() and getMinutes() but it seems to not work on hh:mm formats

CodePudding user response:

   function timePassed(time) {                
        let[hours, mins] = time.split(":");
        console.log(hours);
        console.log(mins);
     //todo: get the hours and minutes from the input value and store them in separate variables
   }
<input type="time" id="timepicker" onchange="timePassed(this.value)">

CodePudding user response:

If you want your time to be displayed in 24-hour increments then the suggestions mentioned above work just fine. If you want it to split it into 12-hour increments then try this.

<input type="time" id="timepicker" onchange="timePassed(this.value)">

<script>
  function timePassed(time) {                
    let [hours, mins] = time.split(":");
    hours = hours/12 > 1 ? hours-12 : hours;
    console.log(hours);
    console.log(mins);
  }
</script>
  • Related