Possible Duplicate:
Formatting a date in JavaScript
How to get datetime in javascript?
I’ve found a script that displays the current date and time in various time zones. I can’t figure out how to change the format. Currently, it displays as MM/DD/YYYY HH:MM:SS AM/PM and I want it to just display as HH:MM AM/PM
I’m more skilled with jQuery than plain JavaScript, and this is confounding me:
$(document).ready(function() {
function calcTime(offset) {
currentDate = new Date();
utc = currentDate.getTime() + (currentDate.getTimezoneOffset() * 60000);
newDate = new Date(utc + (3600000*offset));
return newDate.toLocaleString();
}
function displayTimes() {
$("#chicago").html(calcTime("-6"));
$("#london").html(calcTime("+1"));
$("#shanghai").html(calcTime("+8"));
};
window.setInterval(displayTimes, 1000);
});
The culprit is the following line.
Specifically, toLocaleString()
You can find out more about what that line’s doing here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
A quick way would be to use .toTimeString()
Instead of returning newDate.toLocaleString() or .toTimeString() you want to make it print as you wish it to.
e.g.
That’ll give you the military time.
If you want am/pm display, this can get that for you
If you want the time prettified, 0 is 12 midnight, and 12 is noon. You can subtract 12 if the hours are greater than 12. If 0, you can also set it to display 12. All that can be done like this:
Should definitely use a var for newDate.getHours(). Speaking of vars…
Please reformat your vars as such:
var currentDate = new Date(),
utc = currentDate.getTime() + (currentDate.getTimezoneOffset() * 60000),
newDate = new Date(utc + (3600000*offset));
Hope that helps.
EDIT: All together now:
replace the following
with the following
That’s rather sloppy, and hurriedly written, but if you use a var for newDate.getHours() it’ll be an easier read.
Thanks.