How to get correct gmt time in Javascript

11.8k Views Asked by At

For using the Amazon mechanical turk API I want to get the current GMT time and show it in ISO format

2011-02-24T20:38:34Z

I am wondering if there is any way to correctly get the gmt time and also be able to reformat it with ISO format. I can use something like now.toGMTString(); but it makes a string out of the date and it is hard to reformat it with ISO.

4

There are 4 best solutions below

1
On BEST ANSWER
function pad(num) {
    return ("0" + num).slice(-2);
}

function formatDate(d) {
    return [d.getUTCFullYear(), 
            pad(d.getUTCMonth() + 1), 
            pad(d.getUTCDate())].join("-") + "T" + 
           [pad(d.getUTCHours()), 
            pad(d.getUTCMinutes()), 
            pad(d.getUTCSeconds())].join(":") + "Z";
}

formatDate(new Date());

Output:

"2011-02-24T21:01:55Z"
3
On
var year = now.getUTCFullYear()
var month = now.getUTCMonth()
var day= now.getUTCDay()
var hour= now.getUTCHours()
var mins= now.getUTCMinutes()
var secs= now.getUTCSeconds()

var dateString = year + "-" + month + "-" + day + "T" + hour + ":" + mins + ":" + secs + "Z"

You should be using UTC now instead of GMT. (Amounts to almost the same thing now, and it is the new standard anyway)

2
On

I believe this will work for you:

Number.prototype.pad = function(width,chr){
    chr = chr || '0';
    var result = this;
    for (var a = 0; a < width; a++)
        result = chr + result;
    return result.slice(-width);
}
Date.prototype.toISOString = function(){
    return this.getUTCFullYear().pad(4) + '-'
        + this.getUTCMonth().pad(2) + '-'
        + this.getUTCDay().pad(2) + 'T'
        + this.getUTCHours().pad(2) + ':'
        + this.getUTCMinutes().pad(2) + ':'
        + this.getUTCSeconds().pad(2) + 'Z';
}

Usage:

var d = new Date;
alert('ISO Format: '+d.toISOString());

Not much more different than every else's answer, but make it built-in to the date object for convenience

0
On

This script can take care of it

/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
  + pad(d.getUTCMonth()+1)+'-'
  + pad(d.getUTCDate())+'T'
  + pad(d.getUTCHours())+':'
  + pad(d.getUTCMinutes())+':'
  + pad(d.getUTCSeconds())+'Z'}
var d = new Date();
document.write(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z