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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:30:50  来源:igfitidea点击:

Get a UTC timestamp

javascripttime

提问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

在 Javascript 1.5 下,只需

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 +%son 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/

现场演示http://jsfiddle.net/naryad/uU7FH/1/

回答by abuduba

"... that are independent of their timezone"

“......独立于他们的时区”

var timezone =  d.getTimezoneOffset() // difference in minutes from GMT