I have buttons with the names of big cities.
Clicking them, I want to get local time in them.
$(\'#btnToronto\').click(function () {
var hours = ne
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
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.
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.
The best way without extensions and complex coding:
date.toLocaleString([], { hour12: true});
How do you display javascript datetime in 12 hour AM/PM format?
Try this:
h = h > 12 ? h-12 +'PM' : h +'AM';
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."