When I use the "getHour()" method in javascript, it displays the military time format. I need it to display the hour in numbers between 1-12 instead. Can anybody tell me how to do this? Here is the code I am using:
function updateclock() { var time = new Date(); var todisplay = ''; if (time.getHours() < 10) todisplay += time.getHours(); else todisplay += time.getHours(); if (time.getMinutes() < 10) todisplay += ':0' + time.getMinutes(); else todisplay += ':' + time.getMinutes(); document.getElementById("clock").innerHTML = todisplay; }
Converting 24-Hour Time to 12-Hour Time. Add 12 to the first hour of the day and include "AM." In 24-hour time, midnight is signified as 00:00. So, for midnight hour, add 12 and the signifier "AM" to convert to 12-hour time. This means that, for example, 00:13 in 24-hour time would be 12:13 AM in 12-hour time.
length > 1) { // If time format correct time = time. slice (1); // Remove full string match value time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM time[0] = +time[0] % 12 || 12; // Adjust hours } return time.
Now in-order to convert it to 12 hours format you can take % 12 on the current time. time = 24, then 24%12 → 0 , if the time is 0, then change the time as 12.
Use the toLocaleString() method to change time formatting to 24 hours, e.g. date. toLocaleString('en-US', {hour12: false}) . The toLocaleString method returns a string that represents the date and time according to the provided locale and options parameters.
Why not do it the brief way? Math, people! :)
// returns the hours number for a date, between 1 and 12 function hours12(date) { return (date.getHours() + 24) % 12 || 12; }
This will correct 13 - 24 back to the range 1 - 12, and 0 back to 12:
var hours = time.getHours(); if (hours > 12) { hours -= 12; } else if (hours === 0) { hours = 12; }
Also, you need to stop repeating yourself in your code. Call time.getHours()
and time.getMinutes()
and store their values just once each, and then worry about adding the leading zeroes, e.g.:
function updateclock() { function pad(n) { return (n < 10) ? '0' + n : n; } var time = new Date(); var hours = time.getHours(); var minutes = time.getMinutes(); if (hours > 12) { hours -= 12; } else if (hours === 0) { hours = 12; } var todisplay = pad(hours) + ':' + pad(minutes); document.getElementById("clock").innerHTML = todisplay; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With