Reputation: 73
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
Upvotes: 0
Views: 6521
Reputation: 96
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>
Upvotes: 0
Reputation: 159
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)">
Upvotes: 2