对于使用亚马逊机械土耳其人API我想获得当前的GMT时间并以ISO格式显示
2011-02-24T20:38:34Z
我想知道是否有任何方法可以正确获取gmt时间并且还能够使用ISO格式重新格式化它。我可以使用类似now.toGMTString();
之类的东西,但它会使日期中出现一个字符串,并且很难用ISO重新格式化它。
答案 0 :(得分:5)
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。 (现在几乎是相同的东西,无论如何它都是新标准)
答案 1 :(得分: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());
与其他人的答案没有太大的不同,但为方便起见,请将其内置于日期对象
答案 2 :(得分: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
答案 3 :(得分: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"