483

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

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
bbrame
  • 18,031
  • 10
  • 35
  • 52
  • 3
    Don't waste your time http://stackoverflow.com/a/17538193/3541385 its working.. – Ritesh Jul 15 '16 at 07:15
  • 2
    @Ritesh `WARNING: toLocaleTimeString() may behave differently based on region / location.` Measure twice, cut once. – Abandoned Cart May 06 '19 at 12:40
  • @AbandonedCart is that actually a saying? – gilbert-v May 31 '19 at 14:34
  • 1
    @gilbert-v `One should double-check one's measurements for accuracy before cutting a piece of wood; otherwise it may be necessary to cut again, wasting time and material.` That question is probably better asked on Google, though. – Abandoned Cart May 31 '19 at 14:41
  • 2
    I will **never** get used to how damn convoluted it is trying to work with simple dates in JavaScript. – ashleedawg Mar 02 '20 at 14:31

33 Answers33

786

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));
WasiF
  • 26,101
  • 16
  • 120
  • 128
bbrame
  • 18,031
  • 10
  • 35
  • 52
  • 4
    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. – jrz Nov 15 '12 at 13:28
  • Hi, can you exaplain to me what are you doing with this: minutes = minutes < 10 ? '0'+minutes : minutes; – Balz Jun 27 '13 at 03:43
  • 3
    @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. – Caleb Bell Jun 29 '13 at 21:05
  • for the hours initialization, how about hours = hours%12 || hours ?, – P.M Oct 02 '13 at 18:43
  • 8
    I prefer this `minutes = ('0'+minutes).slice(-2);` rather than `minutes = minutes < 10 ? '0'+minutes : minutes; ` – Vignesh May 22 '15 at 09:22
  • 1
    @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; – Robbie Smith Oct 18 '15 at 23:02
  • 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? – Mohamad Al Asmar Jun 20 '17 at 09:01
  • if (m < 10) {m = "0"+m;} – Halfacht Dec 12 '17 at 10:35
  • `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. – Sam Creamer Sep 09 '19 at 03:03
  • 1
    that should be `hours = hours != 0 ? hours : 12;` – Josh Deese Sep 19 '19 at 20:20
  • 15
    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 https://caniuse.com/?search=toLocaleString – Igor Lutsyk Dec 14 '20 at 01:00
  • @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. – ICW Dec 16 '21 at 15:14
  • not working ... date return is not correct – Ali Yar Khan Feb 11 '22 at 06:18
  • @IgorLutsyk No, what's insane is thinking that everyone wants to use the same format. Your solution does not allow for any custom formatting, and thus, this answer is what is best for most people. Unfortunately, the people who developed the underlying `Date` code did not really make it all that flexible for date time formatting... – Andrew Feb 05 '23 at 01:38
  • To fix the hours so that they display in 12 hour format, you can also use: `(date.getHours() - 1) % 12 + 1` – Andrew Feb 05 '23 at 01:39
418

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

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Abhay Kumar
  • 5,048
  • 2
  • 16
  • 21
49

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.

CodeIt
  • 3,492
  • 3
  • 26
  • 37
Steve Tauber
  • 9,551
  • 5
  • 42
  • 46
  • 4
    People don't use Regex enough. This worked for me without adding the jquery/microsoftajax library suggestions above. – uadrive May 11 '14 at 04:24
  • 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? – RADXack May 16 '17 at 22:38
  • 1
    @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. – Steve Tauber May 18 '17 at 10:11
  • 1
    console.log(new Date().toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")); To get current time – mujaffars Mar 08 '18 at 09:03
  • 1
    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. – Craigo Jan 21 '21 at 00:13
47

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.

rattray
  • 5,174
  • 1
  • 33
  • 27
35

In modern browsers, use Intl.DateTimeFormat and force 12hr format with options:

    let now = new Date();

    new Intl.DateTimeFormat('default',
        {
            hour12: true,
            hour: 'numeric',
            minute: 'numeric'
        }).format(now);

    // 6:30 AM

Using default will honor browser's default locale if you add more options, yet will still output 12hr format.

mtm
  • 691
  • 6
  • 6
33

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?

Community
  • 1
  • 1
Edwin Mendez
  • 522
  • 6
  • 14
22

Use Moment.js for this

Use below codes in JavaScript when using moment.js

H, HH       24 hour time
h, or hh    12 hour time (use in conjunction with a or A)

The format() method returns the date in specific format.

moment(new Date()).format("YYYY-MM-DD HH:mm"); // 24H clock
moment(new Date()).format("YYYY-MM-DD hh:mm A"); // 12H clock (AM/PM)
moment(new Date()).format("YYYY-MM-DD hh:mm a"); // 12H clock (am/pm)
Ankur Mahajan
  • 3,396
  • 3
  • 31
  • 42
19

My suggestion is use moment js for date and time operation.

https://momentjs.com/docs/#/displaying/format/

console.log(moment().format('hh:mm a'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Vijay Maheriya
  • 1,617
  • 16
  • 21
16

Updated for more compression

const formatAMPM = (date) => {
  let hours = date.getHours();
  let minutes = date.getMinutes();    
  const ampm = hours >= 12 ? 'pm' : 'am';

  hours %= 12;
  hours = hours || 12;    
  minutes = minutes < 10 ? `0${minutes}` : minutes;

  const strTime = `${hours}:${minutes} ${ampm}`;

  return strTime;
};

console.log(formatAMPM(new Date()));
OnlyZero
  • 441
  • 5
  • 6
14

use dateObj.toLocaleString([locales[, options]])

Option 1 - Using locales

var date = new Date();
console.log(date.toLocaleString('en-US'));

Option 2 - Using options

var options = { hour12: true };
console.log(date.toLocaleString('en-GB', options));

Note: supported on all browsers but safari atm

LiranBo
  • 2,054
  • 2
  • 23
  • 39
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString – mimo May 06 '16 at 10:10
12

Short RegExp for en-US:

var d = new Date();
d = d.toLocaleTimeString().replace(/:\d+ /, ' '); // current time, e.g. "1:54 PM"
Geo
  • 12,666
  • 4
  • 40
  • 55
  • this doesn´t work on latest safari and firefox browsers, time still uses 24 hour format – euther Mar 06 '14 at 00:34
  • 1
    answers get outdated as time goes by. Feel free to edit and update! – Geo Mar 06 '14 at 18:30
  • 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. – sadmicrowave May 14 '15 at 18:59
  • The output of [*toLocaleTimeString*](http://ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaletimestring) is implementation dependent, so not reliably the same format everywhere. – RobG May 10 '17 at 05:29
11

Please find the solution below

var d = new Date();
var amOrPm = (d.getHours() < 12) ? "AM" : "PM";
var hour = (d.getHours() < 12) ? d.getHours() : d.getHours() - 12;
return   d.getDate() + ' / ' + d.getMonth() + ' / ' + d.getFullYear() + ' ' + hour + ':' + d.getMinutes() + ' ' + amOrPm;
  • 2
    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. – Ryan Apr 18 '19 at 14:05
7

It will return the following format like

09:56 AM

appending zero in start for the hours as well if it is less than 10

Here it is using ES6 syntax

const getTimeAMPMFormat = (date) => {
  let hours = date.getHours();
  let minutes = date.getMinutes();
  const ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  hours = hours < 10 ? '0' + hours : hours;
  // appending zero in the start if hours less than 10
  minutes = minutes < 10 ? '0' + minutes : minutes;
  return hours + ':' + minutes + ' ' + ampm;
};
console.log(getTimeAMPMFormat(new Date)); // 09:59 AM
Irshad Babar
  • 1,311
  • 19
  • 26
5

I fount it's here it working fine.

var date_format = '12'; /* FORMAT CAN BE 12 hour (12) OR 24 hour (24)*/
 
 
var d       = new Date();
var hour    = d.getHours();  /* Returns the hour (from 0-23) */
var minutes     = d.getMinutes();  /* Returns the minutes (from 0-59) */
var result  = hour;
var ext     = '';
 
if(date_format == '12'){
    if(hour > 12){
        ext = 'PM';
        hour = (hour - 12);
        result = hour;

        if(hour < 10){
            result = "0" + hour;
        }else if(hour == 12){
            hour = "00";
            ext = 'AM';
        }
    }
    else if(hour < 12){
        result = ((hour < 10) ? "0" + hour : hour);
        ext = 'AM';
    }else if(hour == 12){
        ext = 'PM';
    }
}
 
if(minutes < 10){
    minutes = "0" + minutes; 
}
 
result = result + ":" + minutes + ' ' + ext; 
 
console.log(result);

and plunker example here

vamsikrishnamannem
  • 4,817
  • 5
  • 23
  • 34
5

Hopefully this answer is a little more readable than the other answers (especially for new comers).

Here's the solution I've implemented in some of my sites for informing the last time the site code was modified. It implements AM/PM time through the options parameter of date.toLocaleDateString (see related Mozilla documentation).

// Last time page code was updated/changed
const options = {
    year: "numeric",
    month: "long",
    weekday: "long",
    day: "numeric",
    hour: "numeric",
    minute: "numeric",
    second: "numeric",
    hour12: true // This is the line of code we care about here
    /*
        false: displays 24hs format for time
        true: displays 12, AM and PM format
    */
};

let last = document.lastModified;
let date = new Date(last);
let local = date.toLocaleDateString("en-US", options);
let fullDate = `${local}`;
document.getElementById("updated").textContent = fullDate;

Which output is in the format:

Saturday, May 28, 2022, 8:38:50 PM

This output is then displayed in the following HTML code:

<p>Last update: <span id="updated">_update_date_goes_here</span></p>

NOTE: In this use case, document.lastModified has some weird behaviors depending if it's run locally or on a external server (see this Stack Overflow question). Though it works correctly when I run it in my GitHub page (you should see it in action in the site at the footer).

carloswm85
  • 1,396
  • 13
  • 23
4
<script>
var todayDate = new Date();
var getTodayDate = todayDate.getDate();
var getTodayMonth =  todayDate.getMonth()+1;
var getTodayFullYear = todayDate.getFullYear();
var getCurrentHours = todayDate.getHours();
var getCurrentMinutes = todayDate.getMinutes();
var getCurrentAmPm = getCurrentHours >= 12 ? 'PM' : 'AM';
getCurrentHours = getCurrentHours % 12;
getCurrentHours = getCurrentHours ? getCurrentHours : 12; 
getCurrentMinutes = getCurrentMinutes < 10 ? '0'+getCurrentMinutes : getCurrentMinutes;
var getCurrentDateTime = getTodayDate + '-' + getTodayMonth + '-' + getTodayFullYear + ' ' + getCurrentHours + ':' + getCurrentMinutes + ' ' + getCurrentAmPm;
alert(getCurrentDateTime);
</script>
Pankaj Upadhyay
  • 2,114
  • 21
  • 22
4

Check out Datejs. Their built in formatters can do this: http://code.google.com/p/datejs/wiki/APIDocumentation#toString

It's a really handy library, especially if you are planning on doing other things with date objects.

Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
3

Here is another way that is simple, and very effective:

        var d = new Date();

        var weekday = new Array(7);
        weekday[0] = "Sunday";
        weekday[1] = "Monday";
        weekday[2] = "Tuesday";
        weekday[3] = "Wednesday";
        weekday[4] = "Thursday";
        weekday[5] = "Friday";
        weekday[6] = "Saturday";

        var month = new Array(11);
        month[0] = "January";
        month[1] = "February";
        month[2] = "March";
        month[3] = "April";
        month[4] = "May";
        month[5] = "June";
        month[6] = "July";
        month[7] = "August";
        month[8] = "September";
        month[9] = "October";
        month[10] = "November";
        month[11] = "December";

        var t = d.toLocaleTimeString().replace(/:\d+ /, ' ');

        document.write(weekday[d.getDay()] + ',' + " " + month[d.getMonth()] + " " + d.getDate() + ',' + " " + d.getFullYear() + '<br>' + d.toLocaleTimeString());

    </script></div><!-- #time -->
3

If you have time as string like so var myTime = "15:30", then you can use the following code to get am pm.

var hour = parseInt(myTime.split(":")[0]) % 12;
var timeInAmPm = (hour == 0 ? "12": hour ) + ":" + myTime.split(":")[1] + " " + (parseInt(parseInt(myTime.split(":")[0]) / 12) < 1 ? "am" : "pm");
salman_sali
  • 181
  • 2
  • 8
2

function startTime() {
  const today = new Date();
  let h = today.getHours();
  let m = today.getMinutes();
  let s = today.getSeconds();
  var meridian = h >= 12 ? "PM" : "AM";
  h = h % 12;
  h = h ? h : 12;
  m = m < 10 ? "0" + m : m;
  s = s < 10 ? "0" + s : s;
  var strTime = h + ":" + m + ":" + s + " " + meridian;
  document.getElementById('time').innerText = strTime;
  setTimeout(startTime, 1000);
}

startTime();
<h1 id='time'></h1>
Muhammad Zakaria
  • 1,269
  • 6
  • 14
1

you can determine am or pm with this simple code

var today=new Date();
var noon=new Date(today.getFullYear(),today.getMonth(),today.getDate(),12,0,0);
var ampm = (today.getTime()<noon.getTime())?'am':'pm';
sarkiroka
  • 1,485
  • 20
  • 28
1

try this

      var date = new Date();
      var hours = date.getHours();
      var minutes = date.getMinutes();
      var seconds = date.getSeconds();
      var ampm = hours >= 12 ? "pm" : "am";
Md. Juyel Rana
  • 540
  • 5
  • 10
  • This is incorrect. The hours could be greater than 12. – Utsav T Apr 14 '20 at 15:02
  • 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. – Md. Juyel Rana Apr 14 '20 at 17:13
  • 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. – Utsav T Apr 14 '20 at 17:29
1

function formatTime( d = new Date(), ampm = true ) 
{
    var hour = d.getHours();
    
    if ( ampm )
    {
        var a = ( hour >= 12 ) ? 'PM' : 'AM';
        hour = hour % 12;
        hour = hour ? hour : 12; // the hour '0' should be '12'  
    }

    var hour    = checkDigit(hour);  
    var minute  = checkDigit(d.getMinutes());
    var second  = checkDigit(d.getSeconds());
  
    // https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript
    return ( ampm ) ? `${hour}:${minute}:${second} ${a}` : `${hour}:${minute}:${second}`;
}

function checkDigit(t)
{
  return ( t < 10 ) ? `0${t}` : t;
}

document.querySelector("#time1").innerHTML = formatTime();
document.querySelector("#time2").innerHTML = formatTime( new Date(), false );
<p>ampm true:   <span id="time1"></span> (default)</p>
<p>ampm false:  <span id="time2"></span></p>
antelove
  • 3,216
  • 26
  • 20
1

If anyone is looking for a 1-liner:

const formatAMPM = date => `${(date.getHours() % 12) || 12}:${date.getMinutes().toString().padStart(2, '0')} ${date.getHours() < 12 ? 'AM' : 'PM'}`    

OR more readable 3-liner (or if you don't have padStart in your browser):

const formatAMPM = (date) => {
  let minutes = date.getMinutes()
  minutes = minutes < 10 ? '0' + minutes : minutes
  return `${(date.getHours() % 12) || 12}:${minutes} ${date.getHours() < 12 ? 'AM' : 'PM'}`
}
pathikrit
  • 32,469
  • 37
  • 142
  • 221
0

var d = new Date();
var hours = d.getHours() % 12;
  hours = hours ? hours : 12;
    var test = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][(d.getMonth() + 1)] + " " + 
    ("00" + d.getDate()).slice(-2) + " " + 
    d.getFullYear() + " " + 
    ("00" + hours).slice(-2) + ":" + 
    ("00" + d.getMinutes()).slice(-2) + ":" + 
    ("00" + d.getSeconds()).slice(-2) + ' ' + (d.getHours() >= 12 ? 'PM' : 'AM'); 
    
document.getElementById("demo").innerHTML = test;
<p id="demo" ></p>
Sujith S
  • 555
  • 5
  • 8
0
<h1 id="clock_display" class="text-center" style="font-size:40px; color:#ffffff">[CLOCK TIME DISPLAYS HERE]</h1>



<script>
            var AM_or_PM = "AM";

            function startTime(){

                var today = new Date();
                var h = today.getHours();
                var m = today.getMinutes();
                var s = today.getSeconds();

                h = twelve_hour_time(h);
                m = checkTime(m);
                s = checkTime(s);



                document.getElementById('clock_display').innerHTML =
                    h + ":" + m + ":" + s +" "+AM_or_PM;
                var t = setTimeout(startTime, 1000);

            }

            function checkTime(i){

                if(i < 10){
                    i = "0" + i;// add zero in front of numbers < 10
                }
                return i;
            }

            // CONVERT TO 12 HOUR TIME. SET AM OR PM
            function twelve_hour_time(h){

                if(h > 12){
                    h = h - 12;
                    AM_or_PM = " PM";
                }
                return h;

            }

            startTime();

        </script>
0

Here my solution

function getTime() {
var systemDate = new Date();
var hours = systemDate.getHours();
var minutes = systemDate.getMinutes();
var strampm;
if (hours >= 12) {
    strampm= "PM";
} else {
    strampm= "AM";
}
hours = hours % 12;
if (hours == 0) {
    hours = 12;
}
_hours = checkTimeAddZero(hours);
_minutes = checkTimeAddZero(minutes);
console.log(_hours + ":" + _minutes + " " + strampm);
}

function checkTimeAddZero(i) {
if (i < 10) {
    i = "0" + i
}
return i;
}
Sumit Shitole
  • 110
  • 1
  • 3
  • 20
Prathamesh More
  • 1,470
  • 2
  • 18
  • 32
0
function getDateTime() {
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var day = now.getDate();

  if (month.toString().length == 1) {
    month = '0' + month;
  }
  if (day.toString().length == 1) {
    day = '0' + day;
  }

  var hours = now.getHours();
  var minutes = now.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  var timewithampm = hours + ':' + minutes + ' ' + ampm;

  var dateTime = monthNames[parseInt(month) - 1] + ' ' + day + ' ' + year + ' ' + timewithampm;
  return dateTime;
}
Vik2696
  • 347
  • 2
  • 7
0
   const formatAMPM = (date) => {
    try {
      let time = date.split(" ");
      let hours = time[4].split(":")[0];
      let minutes = time[4].split(":")[1];
      hours = hours || 12;
      const ampm = hours >= 12 ? " PM" : " AM";
      minutes = minutes < 10 ? `${minutes}` : minutes;
      hours %= 12;
      const strTime = `${hours}:${minutes} ${ampm}`;
      return strTime;
    } catch (e) {
      return "";
    }
  };

const startTime = "2021-12-07T17:00:00.073Z"
formatAMPM(new Date(startTime).toUTCString())
Mitesh K
  • 694
  • 1
  • 11
  • 24
0

This is the easiest Way you can Achieve this using ternary operator or you can also use if else instead !

const d = new Date();
let hrs = d.getHours();
let m = d.getMinutes();
// Condition to add zero before minute
let min = m < 10 ? `0${m}` : m;
const currTime = hrs >= 12 ? `${hrs - 12}:${min} pm` : `${hrs}:${min} am`;
console.log(currTime);
Abhishek
  • 81
  • 6
0

{new Date(progress.position * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }).substring(0,5)}

-1

Or just simply do the following code:

    <script>
        time = function() {
            var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
            m = checkTime(m);
            s = checkTime(s);
            document.getElementById('txt_clock').innerHTML = h + ":" + m + ":" + s;     
            var t = setTimeout(function(){time()}, 0);
        }

        time2 = function() {
            var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
            m = checkTime(m);
            s = checkTime(s);
            if (h>12) {
                document.getElementById('txt_clock_stan').innerHTML = h-12 + ":" + m + ":" + s;
            }               
            var t = setTimeout(function(){time2()}, 0);
        }

        time3 = function() {
            var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
            if (h>12) {
                document.getElementById('hour_line').style.width = h-12 + 'em'; 
            }
            document.getElementById('minute_line').style.width = m + 'em';  
            document.getElementById('second_line').style.width = s + 'em';  
            var t = setTimeout(function(){time3()}, 0);
        }

        checkTime = function(i) {
            if (i<10) {i = "0" + i};  // add zero in front of numbers < 10
            return i;
        }           
    </script>

Glenn Randers-Pehrson
  • 11,940
  • 3
  • 37
  • 61
-1

A short and sweet implementation:

// returns date object in 12hr (AM/PM) format
var formatAMPM = function formatAMPM(d) {
    var h = d.getHours();
    return (h % 12 || 12)
        + ':' + d.getMinutes().toString().padStart(2, '0')
        + ' ' + (h < 12 ? 'A' : 'P') + 'M';
};
johnchinjew
  • 150
  • 1
  • 1
  • 6