How do you display JavaScript datetime in 12hour AM/PM format?



We can extract the hours and minutes from current date time. If the hours value is greater than 12 then it will be PM, otherwise AM.

Example

Following is the code −

function dateTOAMORPM(currentDateTime) {
   var hrs = currentDateTime.getHours();
   var mnts = currentDateTime.getMinutes();
   var AMPM = hrs >= 12 ? 'PM' : 'AM';
   hrs = hrs % 12;
   hrs = hrs ? hrs : 12;
   mnts = mnts < 10 ? '0' + mnts : mnts;
   var result = hrs + ':' + mnts + ' ' + AMPM;
   return result;
}
console.log(dateTOAMORPM(new Date()));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo276.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo276.js
7:26 PM

Advertisements