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 ?

qadenza
  • 9,025
  • 18
  • 73
  • 126
  • 1
    Mmmm... divide by 12? modulo? – elclanrs Jun 08 '13 at 19:47
  • 1
    @elclanrs, `hours` is for example `19`. Divide by 12... what? – qadenza Jun 08 '13 at 19:50
  • 1
    if `hours < 12` so it is PM , otherwise it is AM , no? – Ivan Chernykh Jun 08 '13 at 19:51
  • @SunSky: lol. I messed up, my bad. I posted my answer tho, hope that helps. – elclanrs Jun 08 '13 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. – Matt Johnson-Pint Jun 09 '13 at 04:12
  • I have given the answer here https://stackoverflow.com/a/58892934/6516699. Simply and yet powerful – Naren Nov 16 '19 at 16:45

13 Answers13

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.

earlonrails
  • 4,966
  • 3
  • 32
  • 47
J W
  • 1,778
  • 1
  • 11
  • 15
  • Consider: is midnight _a.m._ or _p.m._ ? What does that mean for noon? What will this say noon is? – Paul S. Jun 08 '13 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 08 '13 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);
});
Chirag K
  • 2,394
  • 2
  • 16
  • 23
TechBytes
  • 563
  • 5
  • 16
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.

  • 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 '20 at 03:26
9
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";

Dilan
  • 2,610
  • 7
  • 23
  • 33
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."
Paul S.
  • 64,864
  • 9
  • 122
  • 138
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;

}
jeremy-denis
  • 6,368
  • 3
  • 18
  • 35
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

Sameera R.
  • 4,384
  • 2
  • 36
  • 53
2

Try this:

h = h > 12 ? h-12 +'PM' : h +'AM';
elclanrs
  • 92,861
  • 21
  • 134
  • 171
1

The best way without extensions and complex coding:

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

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

Community
  • 1
  • 1
Edwin Mendez
  • 522
  • 6
  • 14
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
user889030
  • 4,353
  • 3
  • 48
  • 51
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;
Vik2696
  • 347
  • 2
  • 7
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,

Prabhat kumar
  • 532
  • 1
  • 4
  • 17
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>
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61