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

615,106

Solution 1

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

Solution 2

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

Solution 3

Here's a way using regex:

console.log(new Date('7/10/2013 20:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"))
console.log(new Date('7/10/2013 01:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"))

This creates 3 matching groups:

  • ([\d]+:[\d]{2}) - Hour:Minute
  • (:[\d]{2}) - Seconds
  • (.*) - the space and period (Period is the official name for AM/PM)

Then it displays the 1st and 3rd groups.

WARNING: toLocaleTimeString() may behave differently based on region / location.

Solution 4

If you don't need to print the am/pm, I found the following nice and concise:

var now = new Date();
var hours = now.getHours() % 12 || 12;  // 12h instead of 24h, with 12 instead of 0. 

This is based off @bbrame's answer.

Solution 5

As far as I know, the best way to achieve that without extensions and complex coding is like this:

     date.toLocaleString([], { hour12: true});

Javascript AM/PM Format

<!DOCTYPE html>
<html>
<body>
    <p>Click the button to display the date and time as a string.</p>

    <button onclick="myFunction()">Try it</button>
    <button onclick="fullDateTime()">Try it2</button>
    <p id="demo"></p>
    <p id="demo2"></p>
    <script>
        function myFunction() {
            var d = new Date();
            var n = d.toLocaleString([], { hour: '2-digit', minute: '2-digit' });
            document.getElementById("demo").innerHTML = n;
        }
        function fullDateTime() {
            var d = new Date();          
            var n = d.toLocaleString([], { hour12: true});
            document.getElementById("demo2").innerHTML = n;
        }
    </script>
</body>
</html>

I found this checking this question out.

How do I use .toLocaleTimeString() without displaying seconds?

Share:
615,106
bbrame
Author by

bbrame

Updated on July 08, 2022

Comments

  • bbrame
    bbrame almost 2 years

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

  • Jon z
    Jon z over 11 years
    Also you declared the "hours" variable twice but made "strTime" an accidental global. It's not extremely elegant but this seems to be the proper technique using native methods.
  • Balz
    Balz almost 11 years
    Hi, can you exaplain to me what are you doing with this: minutes = minutes < 10 ? '0'+minutes : minutes;
  • Caleb Bell
    Caleb Bell almost 11 years
    @Balz If minutes is less than 10 (e.g. 16:04), then that statement adds the string "0" so that the formatted output is "4:04 PM" instead of "4:4 PM". Note that in the process, minutes changes from a Number to a String.
  • P.M
    P.M over 10 years
    for the hours initialization, how about hours = hours%12 || hours ?,
  • euther
    euther about 10 years
    this doesn´t work on latest safari and firefox browsers, time still uses 24 hour format
  • Geo
    Geo about 10 years
    answers get outdated as time goes by. Feel free to edit and update!
  • uadrive
    uadrive about 10 years
    People don't use Regex enough. This worked for me without adding the jquery/microsoftajax library suggestions above.
  • rattray
    rattray about 9 years
    @koolinc for midnight it shows 12. I'm not sure what else the desired behavior would be.
  • KooiInc
    KooiInc about 9 years
    I stand corrected. In my country the 24-hour clock is used, so I'm not that familiar with the 12-hour clock. Indeed midnight is 12:00am.
  • sadmicrowave
    sadmicrowave about 9 years
    This actually will make the string look like 1:54 PM CDT. To remove the CDT alter your regex to the following .replace(/:\d+ |\CDT/g, ' '). Although, CDT is just my timezone. If you have a different timezone I suppose you would need to change to that zone code.
  • Vignesh
    Vignesh almost 9 years
    I prefer this minutes = ('0'+minutes).slice(-2); rather than minutes = minutes < 10 ? '0'+minutes : minutes;
  • Robbie Smith
    Robbie Smith over 8 years
    @Vignesh solution for the minutes is better because if you're doing the one suggestioned 21:00:00 becomes 9:000. Vignesh's gives you the correct minutes as :00. If you were to use the above solution then you'd have to account for the 00 as well. (mintues>0 && minutes < 10) ? '0'+minutes : minutes;
  • mimo
    mimo about 8 years
  • reutsey
    reutsey over 7 years
    What about hour, minutes, and AM/PM?
  • RobG
    RobG about 7 years
    Answers like "use library X" are not helpful. They can be good as comments though.
  • RobG
    RobG about 7 years
    The output of toLocaleTimeString is implementation dependent, so not reliably the same format everywhere.
  • Chris Laplante
    Chris Laplante about 7 years
    @RobG: As you can see it's been quite a while since I wrote this answer. I realize this now.
  • RADXack
    RADXack about 7 years
    What would be the regex be to have a trailing zero at the beginning of the hour if it was a single digit. Say in your first example of 8:12 PM it would be 08:12 PM?
  • Steve Tauber
    Steve Tauber about 7 years
    @404 it's the same, ([\d]+:[\d]{2}) is the part we are interested in. Use the colon (:) as the separator and we see the first part is [\d]+. The plus means one or more. So it's looking for one or more digit (including zero. If you had to guarantee a zero is there, it would be (0[\d]:[\d]{2}). This now reads, look for 0 plus one other digit, then colon, then the rest.
  • Mohamad Al Asmar
    Mohamad Al Asmar almost 7 years
    This returns only the time in AM/PM, I need all the date object to be returned including time in AM/PM, is that possible?
  • Halfacht
    Halfacht over 6 years
    if (m < 10) {m = "0"+m;}
  • lfender6445
    lfender6445 over 6 years
    As of Feb 2018 its working just fine on chrome Neolisk - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • mujaffars
    mujaffars about 6 years
    console.log(new Date().toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2‌​})(.*)/, "$1$3")); To get current time
  • Lynnell Neri
    Lynnell Neri almost 6 years
    Getting the module of the hour with 12 is excellent! This prevents getting zero when it's 12AM or it's 12PM
  • Humble Dolt
    Humble Dolt over 5 years
    it should return 07:23, IMO
  • hon2a
    hon2a over 5 years
    @HumbleDolt You might be confusing 'numeric' with '2-digit'.
  • Robin Métral
    Robin Métral about 5 years
    @Katie in 2019 too
  • Steven Ventimiglia
    Steven Ventimiglia about 5 years
    Source: caniuse.com/#search=toLocaleString() - "...supported in effectively all browsers (since IE6+, Firefox 2+, Chrome 1+ etc)"
  • Ryan
    Ryan about 5 years
    Should be less than or equal to for hour calculation else noon shows up as 0. So: var hour = (d.getHours() <= 12). Still has issue with midnight so you have to check if zero then set to 12 too.
  • Sam Creamer
    Sam Creamer over 4 years
    hours = hours ? hours : 12; I don't really love this for readability. This is leveraging the fact that 0 is the integer equivalent of false in the day. But logically, it is actually the 0 hour of the day. In my few, should be compared to 0 for readability. hours = hours == 0 ? hours : 12;. Coming back to that code in 3 months will probably be easier.
  • Josh Deese
    Josh Deese over 4 years
    that should be hours = hours != 0 ? hours : 12;
  • Scot Nery
    Scot Nery about 4 years
    to use this, assign the new string to a variable eg: let result = new Intl.DateTi.... alert(result);
  • Utsav T
    Utsav T about 4 years
    This is incorrect. The hours could be greater than 12.
  • Md. Juyel Rana
    Md. Juyel Rana about 4 years
    When 12.00 pm the var ampm will be "pm". So 12.00 PM to 11.00 PM hours will be 12 to 23 that store "pm" value and for others, var ampm will store "am" value. Hope you understand.
  • Utsav T
    Utsav T about 4 years
    Hi Juyel ! Indeed when the hours is greater than 12, the value would be PM. But the question is "How do you display JavaScript datetime in 12 hour AM/PM format?" - you need to help OP convert the entire time to the AM/PM format. For example, 14:30 would be 2:30 PM.
  • krupesh Anadkat
    krupesh Anadkat over 3 years
    Sweet, pretty concise
  • Omar
    Omar over 3 years
    this is the best answer but how do you change the capitalization of AM/PM
  • Igor Lutsyk
    Igor Lutsyk over 3 years
    this is insane, that one has proposed to build a wheel from a scratch, if we have JS built-in stuff for that, and it got so many votes and showed as best answer. Downvoting it, and personally do not like this kind of attitude, I can implement that myself, before checking if there is some good built-in solution for your problem, that is well tested, maintained and recommended. Just take a look to toLocaleString it can format JS DateTime in so many ways, including your case. And is supported by all browsers from ancient times caniuse.com/?search=toLocaleString
  • Craigo
    Craigo over 3 years
    Doesn't work in Australia. new Date('7/10/2013 20:12:34').toLocaleTimeString() gives 20:12:34, and regex just gave 20:12. @abhay-kumar answer time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true }) worked.
  • Raul A.
    Raul A. about 3 years
    This is the most simple answer. Vote up because is a javascript native solution. Thanks
  • Thameem
    Thameem about 3 years
    Working in 2021 Covid time too. This answer is much simpler than the above
  • Qumber
    Qumber almost 3 years
    This is a nice native solution.
  • Dem Pilafian
    Dem Pilafian almost 3 years
    Can also do: const time = new Date().toLocaleString([], { hour: 'numeric', minute: 'numeric' }); //"6:30 AM"
  • Allen Gingrich
    Allen Gingrich over 2 years
    This should absolutely be the accepted answer.
  • Spikatrix
    Spikatrix over 2 years
    Great answer! Here's a link to the MDN docs for information on the options if anyone needs it: Intl.DateTimeFormat()
  • ICW
    ICW over 2 years
    @IgorLutsyk is right. No way this function should be written by hand. Plus, this function gets AMPM wrong! If your hour is 0 (12 AM), it incorrectly calculate the AM PM as PM. Just another reason it shouldn't be written by hand.
  • Ali Yar Khan
    Ali Yar Khan over 2 years
    not working ... date return is not correct
  • APu
    APu about 2 years
    This method is perfect if need only hour in 12 hr format
  • Banjali
    Banjali about 2 years
    This 12H format saved my day, thanks.
  • Ankur Mahajan
    Ankur Mahajan about 2 years
    @Banjali, thanks for the appriciation. Please upvote if it helped you.