40

I have buttons with the names of big cities.
Clicking them, I want to get local time in them.

$('#btnToronto').click(function () {
    var hours = new Date().getHours();
    var hours = hours-2; //this is the distance from my local time
    alert ('Toronto time: ' + hours + ' h'); //this works correctly
});

But how can I get AM or PM ?

6
  • 1
    Mmmm... divide by 12? modulo?
    – elclanrs
    Jun 8, 2013 at 19:47
  • 1
    @elclanrs, hours is for example 19. Divide by 12... what?
    – qadenza
    Jun 8, 2013 at 19:50
  • 1
    if hours < 12 so it is PM , otherwise it is AM , no? Jun 8, 2013 at 19:51
  • @SunSky: lol. I messed up, my bad. I posted my answer tho, hope that helps.
    – elclanrs
    Jun 8, 2013 at 19:52
  • Why would you think you should subtract two hours? That makes no sense. The date you get back from new Date() will already be in your local time, unless your computer's time zone setting is wrong. And if you were thinking about time zone offsets from UTC, Toronto is -0500 during standard time and -0400 during daylight time. It's never -0200. And .getHours() returns the hours in local time anyway. Jun 9, 2013 at 4:12

13 Answers 13

42

You should just be able to check if hours is greater than 12.

var ampm = (hours >= 12) ? "PM" : "AM";

But have you considered the case where the hour is less than 2 before you subtract 2? You'd end up with a negative number for your hour.

2
  • Consider: is midnight a.m. or p.m. ? What does that mean for noon? What will this say noon is?
    – Paul S.
    Jun 8, 2013 at 19:55
  • @PaulS. Quite right - fixed for noon. Midnight should come back as 0 and should be am, so that at least should have worked.
    – J W
    Jun 8, 2013 at 20:02
23

Try below code:

$('#btnToronto').click(function () {
    var hours = new Date().getHours();
    var hours = (hours+24-2)%24; 
    var mid='am';
    if(hours==0){ //At 00 hours we need to show 12 am
    hours=12;
    }
    else if(hours>12)
    {
    hours=hours%12;
    mid='pm';
    }
    alert ('Toronto time: ' + hours + mid);
});
3
  • Confused, but I will try all the solutions. Solved (I hope).
    – qadenza
    Jun 8, 2013 at 20:01
  • 5
    What happens if the time is before 2 a.m. before adjusting hours?
    – Paul S.
    Jun 8, 2013 at 20:04
  • This code is incorrect for 12:00 pm. In that case, you need to leave hours set to 12, but change mid to 'pm'.
    – dmboucher
    Jun 3, 2022 at 21:33
13

You can use like this,

var dt = new Date();
    var h =  dt.getHours(), m = dt.getMinutes();
    var _time = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');

Hopes this will be better with minutes too.

1
  • This doesn't work with the hour of 12 noon unfortunately. Times are PM when hours >= 12, but you only subtract 12 when hours >= 13
    – Trent
    Nov 26, 2020 at 3:26
10
const now = new Date()
      .toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true })
      .toLowerCase();

Basically you just need to put {hour12: true} and it's done.

result => now = "21:00 pm";

4

If hours is less than 12, it's the a.m..

var hours = new Date().getHours(), // this is local hours, may want getUTCHours()
    am;
// adjust for timezone
hours = (hours + 24 - 2) % 24;
// get am/pm
am = hours < 12 ? 'a.m.' : 'p.m.';
// convert to 12-hour style
hours = (hours % 12) || 12;

Now, for me as you didn't use getUTCHours, it is currently 2 hours after

hours + ' ' + am; // "6 p.m."
4

very interesting post. in a function that take a date in parameter it can appear like that :

function hourwithAMPM(dateInput) {
   var d = new Date(dateInput);
   var ampm = (d.getHours() >= 12) ? "PM" : "AM";
   var hours = (d.getHours() >= 12) ? d.getHours()-12 : d.getHours();

   return hours+' : '+d.getMinutes()+' '+ampm;

}
3

with date.js

<script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>

you can write like this

new Date().toString("hh:mm tt")

cheet sheet is here format specifiers
tt is for AM/PM

2

Try this:

h = h > 12 ? h-12 +'PM' : h +'AM';
1
  • 1
    Consider; is 12:30 (noon) am or pm? What will this code say it is?
    – Paul S.
    Jun 8, 2013 at 20:01
2

The best way without extensions and complex coding:

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

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

1

here is get time i use in my code

let current = new Date();
let cDate = current.getDate() + '-' + (current.getMonth() + 1) + '-' + current.getFullYear();
let hours = current.getHours();
let am_pm = (hours >= 12) ? "PM" : "AM";

if(hours >= 12){
    hours -=12;
}

let cTime = hours + ":" + current.getMinutes() + ":" + current.getSeconds() +" "+ am_pm;
let dateTime = cDate + ' ' + cTime;

console.log(dateTime);   // 1-3-2021 2:28:14 PM
0
var now = new Date();
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;
return timewithampm;
0
var dt = new Date();
var h = dt.getHours(),
  m = dt.getMinutes();
var time;
if (h == 12) {
  time = h + ":" + m + " PM";
} else {
  time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
}
//var time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";

console.log(`CURRENT TIME IS ${time}`);

This will work for everytime,

0
0

function Timer() {
    var dt = new Date()
    if (dt.getHours() >= 12){
        ampm = "PM";
    } else {
        ampm = "AM";
    }
    if (dt.getHours() < 10) {
        hour = "0" + dt.getHours();
    } else {
        hour = dt.getHours();
    }
    if (dt.getMinutes() < 10) {
        minute = "0" + dt.getMinutes();
    } else {
        minute = dt.getMinutes();
    }
    if (dt.getSeconds() < 10) {
        second = "0" + dt.getSeconds();
    } else {
        second = dt.getSeconds();
    }
    if (dt.getHours() > 12) {
        hour = dt.getHours() - 12;
    } else {
        hour = dt.getHours();
    }
    if (hour < 10) {
        hour = "0" + hour;
    } else {
        hour = hour;
    }
    document.getElementById('time').innerHTML = hour + ":" + minute + ":" + second + " " + ampm;
    setTimeout("Timer()", 1000);
}
Timer()
<div id="time"></div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.