如何在 Javascript 中获得正确的 gmt 时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5110265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get correct gmt time in Javascript
提问by Mark
For using the Amazon mechanical turk API I want to get the current GMT time and show it in ISO format
对于使用 Amazon Mechanical turk API,我想获取当前的 GMT 时间并以 ISO 格式显示
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.
我想知道是否有任何方法可以正确获取 gmt 时间并且还能够使用 ISO 格式重新格式化它。我可以使用类似的东西,now.toGMTString();但它会使字符串过时,并且很难用 ISO 重新格式化它。
回答by Simon David Kelly
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)
您现在应该使用 UTC 而不是 GMT。(现在几乎是一样的,无论如何它都是新标准)
回答by Brad Christie
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
与其他人的答案没有太大不同,但为了方便起见,将其内置到日期对象中
回答by Mark
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
回答by Wayne
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"

