How do you display a JavaScript datetime object in the 12 hour format (AM/PM)?
You have the formatAMPM function, which will take a JavaScript date object as a parameter. Call getHours to get the hours in the 24-hour format in the function and minutes to get the minutes. Then, create the ampm variable and set it to am or pm depending on the value of hours.
There are two patterns that we can use in SimpleDateFormat to display time. Pattern “hh:mm aa” and “HH:mm aa”, here HH is used for 24 hour format without AM/PM and the hh is used for 12 hour format with AM/PM. aa – AM/PM marker. In this example we are displaying current date and time with AM/PM marker.
function formatAMPM(date) { var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0'+minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; } console.log(formatAMPM(new Date));
If you just want to show the hours then..
var time = new Date(); console.log( time.toLocaleString('en-US', { hour: 'numeric', hour12: true }) );
Output : 7 AM
If you wish to show the minutes as well then...
var time = new Date(); console.log( time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true }) );
Output : 7:23 AM
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