JavaScript - 解析 UTC 日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32252565/
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-23 07:48:56  来源:igfitidea点击:

JavaScript - Parse UTC Date

javascriptdate

提问by Artem Kalinchuk

How can I parse a simple date string and let JavaScript know that it's actually a UTC date? Currently, if I do new Date('2015-08-27')it converts it to my timezone.

如何解析一个简单的日期字符串并让 JavaScript 知道它实际上是一个 UTC 日期?目前,如果我这样做new Date('2015-08-27'),会将其转换为我的时区。

回答by potatopeelings

You can do append 'T00:00:00.000Z'to make the time zone specific (Zindicates UTC)

您可以执行 append'T00:00:00.000Z'以使时区特定(Z表示 UTC)

new Date('2015-08-27' + 'T00:00:00.000Z')

Note that new Date('2015-08-27')is treated differently in ES5 (UTC) vs. ES6 (Local), so you can't expect it any correction to be work consistently if you were planning to to hard code it (i.e. don't do it)

请注意,new Date('2015-08-27')在 ES5 (UTC) 和 ES6 (Local) 中的处理方式不同,因此如果您打算对其进行硬编码(即不这样做),则不能指望任何更正都能始终如一地工作



Also, do note that your console.logmight show you the local time corresponding to the UTC time the expression evaluates to (that tends to throw you off a bit if you are expecting UTC to be at the end for expression that evaluate to UTC times and your local time zone at the end for those that evaluate to your local time). For instance

另外,请注意,您console.log可能会向您显示与表达式计算的 UTC 时间相对应的本地时间(如果您期望 UTC 位于计算为 UTC 时间的表达式的末尾,并且您的本地时间)对于那些以您的本地时间进行评估的时区)。例如

new Date('2015-08-27T00:00:00.000Z')

could show

可以显示

Thu Aug 27 2015 1:00:00 GMT+100

which is the sameas

这是相同

Thu Aug 27 2015 00:00:00 UTC

回答by Max Pringle

Here is what I would do.

这就是我要做的。

var current = new Date();
var utcDate = new Date(current.getTime() + current.getTimezoneOffset() * 60000);