Search code examples
javascriptdatetimedatetimeformat

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)?


Solution

  • 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