JavaScript date and time setting

Possible duplicate:
Date formatting in JavaScript
How to get datetime in javascript?

I found a script that displays the current date and time in different time zones. I cannot figure out how to change the format. It currently displays as MM/DD/YYYY HH:MM:SS AM/PM

, and I want it to just display asHH:MM AM/PM

I am more into jQuery than plain JavaScript and it scares 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);
});

      

+3


source to share


2 answers


The culprit is the next line.

    return newDate.toLocaleString();

      

In particular, toLocaleString ()

You can read more about what this line does here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

The quick way is to use .toTimeString ()

Instead of returning newDate.toLocaleString () or .toTimeString (), you want to do the printing the way you want.

eg.

    return newDate.getHours() + ':' newDate.getMinutes();

      

This will give you wartime.

If you want to show am / pm this might get it for you

(newDate.getHours() >  11) ? 'pm' : 'am'

      



If you want the time to be canceled, 0 is 12 midnight and 12 is noon. You can subtract 12 if the clock is greater than 12. If 0, you can also customize the display to 12. All of this can be done as follows:

 (newDate.getHours() === 0) ? 12 : ((newDate.getHours() > 12) ? newDate.getHours() - 12 : newDate.getHours());

      

Make sure to use 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 it helps.

EDIT: Putting it all together now: replace the following

return newDate.toLocaleString();

      

with the following

return (newDate.getHours() === 0) ? 12 : ((newDate.getHours() > 12) ? newDate.getHours() - 12 : newDate.getHours()) + ' : ' + newDate.getMinutes() + ' ' + (newDate.getHours() >  11) ? 'pm' : 'am';

      

This is pretty sloppy and hastily written, but if you use var for newDate.getHours () it will be easier to read.

Thank.

+2


source


var myDate= new Date();
myDate.format("h:mm tt"); 

      



http://www.jslab.dk/library/date.format

-2


source







All Articles