Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do you display a JavaScript datetime object in the 12 hour format (AM/PM)?

like image 333
bbrame Avatar asked Jan 17 '12 01:01

bbrame


People also ask

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

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.

How do I display AM PM in date format?

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.


2 Answers

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));
like image 84
bbrame Avatar answered Oct 21 '22 08:10

bbrame


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

like image 36
Abhay Kumar Avatar answered Oct 21 '22 07:10

Abhay Kumar