Javascript 获取 UTC 时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8047616/
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
Get a UTC timestamp
提问by bgcode
How can I get the current UTC timestamp in JavaScript? I want to do this so I can send timestamps from the client-side that are independent of their timezone.
如何在 JavaScript 中获取当前的 UTC 时间戳?我想这样做,以便我可以从客户端发送独立于时区的时间戳。
回答by ExpExc
new Date().getTime();
For more information, see @James McMahon's answer.
有关更多信息,请参阅@James McMahon 的回答。
回答by James McMahon
As wizzardpointed out, the correct method is,
正如wizzard指出的那样,正确的方法是,
new Date().getTime();
or under Javascript 1.5, just
Date.now();
From the documentation,
从文档中,
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
getTime 方法返回的值是自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数。
If you wanted to make a time stamp without milliseconds you can use,
如果你想制作一个没有毫秒的时间戳,你可以使用,
Math.floor(Date.now() / 1000);
I wanted to make this an answer so the correct method is more visible.
我想把它作为一个答案,这样正确的方法就更明显了。
You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/or by running date +%s
on a Unix terminal.
您可以将 ExpExc 和 Narendra Yadala 的结果与http://jsfiddle.net/JamesFM/bxEJd/ 上的上述方法进行比较,并使用http://www.unixtimestamp.com/或date +%s
在 Unix 终端上运行进行验证。
回答by Narendra Yadala
You can use Date.UTCmethod to get the time stamp at the UTC timezone.
您可以使用Date.UTC方法获取 UTC 时区的时间戳。
Usage:
用法:
var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() ,
now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
Live demo here http://jsfiddle.net/naryad/uU7FH/1/
回答by abuduba
"... that are independent of their timezone"
“......独立于他们的时区”
var timezone = d.getTimezoneOffset() // difference in minutes from GMT