Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get AM or PM?

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 ?

like image 600
qadenza Avatar asked Jun 08 '13 19:06

qadenza


People also ask

Why do we use AM and PM?

am stands for the Latin ante meridiem, translating to "before midday". This is the time before the sun has crossed the meridian. pm stands for post meridiem or "after midday" – after the sun has crossed the meridian.

How do you write AM and PM in JavaScript?

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

How do I show AM PM in C#?

if you use "HH" -> The hour, using a 24-hour clock from 00 to 23. if you use "mm" -> The minute, from 00 through 59. if you use "m" - > The minute, from 0 through 59. if you add "tt" -> The Am/Pm designator.


3 Answers

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.

like image 175
J W Avatar answered Oct 20 '22 09:10

J W


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);
});
like image 39
TechBytes Avatar answered Oct 20 '22 09:10

TechBytes


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.

like image 13
Naren Srinivasan S Avatar answered Oct 20 '22 10:10

Naren Srinivasan S