0

为了使用 Amazon Mechanical turk API,我想获取当前的 GMT 时间并以 ISO 格式显示

2011-02-24T20:38:34Z

我想知道是否有任何方法可以正确获取 gmt 时间并能够使用 ISO 格式重新格式化它。我可以使用类似的东西,now.toGMTString();但它会使字符串过时,并且很难用 ISO 重新格式化它。

4

4 回答 4

4
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"

您现在应该使用 UTC 而不是 GMT。(现在几乎是一样的东西,无论如何它是新标准)

于 2011-02-24T21:05:44.990 回答
3

我相信这对你有用:

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';
}

用法:

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

与其他所有人的答案没有太大不同,但为方便起见,将其内置到日期对象中

于 2011-02-24T21:05:53.200 回答
2
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());

输出:

"2011-02-24T21:01:55Z"
于 2011-02-24T21:20:34.317 回答
2

这个脚本可以处理它

/* 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
于 2011-02-24T21:11:41.687 回答