简体   繁体   English

Javascript:您能像新的Date(localTime +'GMT')这样将本地时间转换为GMT吗?

[英]Javascript: Can you convert your local time to GMT like so, new Date(localTime + 'GMT')?

I currently have a var dateNow as '10 1 2016' and var timeNow as '05:15:50' and was able to convert to UTC like so var dateTimeNow = Date(dateNow + timeNow + ' UTC'); 我目前有一个var dateNow'10 1 2016'var timeNow'05:15:50'并能够像这样转换为UTC var dateTimeNow = Date(dateNow + timeNow + ' UTC');

Would now like to convert it to GMT, so is it as simple as just changing ' UTC' to ' GMT' ? 现在是否要将其转换为GMT,是否像将' UTC'更改为' GMT'一样简单? So like, var dateTimeNow = Date(dateNow + timeNow + ' GMT'); 就像var dateTimeNow = Date(dateNow + timeNow + ' GMT'); ?

If you have a date like "10 1 2016" (Which I guess is 10 January, 2016) and a time like "05:15:50" then you can create a date for that time in a timezone with a zero offset as an ISO 8601 formatted string: "2016-01-10T15:15:50Z" or "2016-01-10T15:15:50+0000". 如果您有一个日期,例如“ 10 1 2016”(我想是2016年1月10日),而时间则是“ 05:15:50”,那么您可以在时区中以零偏移量为该日期创建一个日期作为ISO 8601格式的字符串:“ 2016-01-10T15:15:50Z”或“ 2016-01-10T15:15:50 + 0000”。

An ISO 8601 extended format string should be parsed correctly in modern implementations, however in general it's not a good idea to parse strings with the Date constructor (or Date.parse, they are equivalent for parsing) due to variances in implementations. 在现代实现中应正确解析ISO 8601扩展格式字符串,但是通常由于实现中的差异,使用Date构造函数(或Date.parse,它们等同于解析)来解析字符串不是一个好主意。 If you have a single format, it can be parsed in a couple of lines. 如果您使用的是单一格式,则可以将其解析为几行。 Alternatively, use one of the many Date libraries that have a parser and formatter and remember to always give the parser the format of the string you wish it to parse. 或者,使用具有解析器和格式化程序的许多Date库之一,并记住始终为解析器提供希望解析的字符串格式。

As for converting a local time to UTC, you must know the time zone offset of the local time, otherwise you have no datum to adjust it. 对于将本地时间转换为UTC,您必须知道本地时间的时区偏移量,否则就没有基准可以进行调整。

To "convert" a local date like 10 January, 2016 at 05:15:50 to UTC (where "local" is whatever the host system time zone is set to) is a simple as: 要将“本地”日期(例如2016年1月10日05:15:50)“转换”为UTC(其中“本地”是指主机系统时区设置的任何内容),方法很简单:

 var d = new Date(2016,0,10,5,15,50); console.log('Local: ' + d.toLocaleString() + '\\nUTC: ' + d.toISOString()); 

Note that toLocaleString is entirely implementation dependent, often ignores browser and system settings and produces a different result in different implementations. 请注意, toLocaleString完全取决于实现,通常会忽略浏览器和系统设置,并在不同的实现中产生不同的结果。

This allows the host to consider the current system time zone settings and apply them when creating the date. 这使主机可以考虑当前系统时区设置,并在创建日期时应用它们。 ECMAScript Date objects have a time value that is based on UTC, so they are inherently UTC. ECMAScript Date对象具有基于UTC的时间值,因此它们本质上是UTC。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM