Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

javascript - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...