Javascript 如何将日期转换为 GMT?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8945029/
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 can I convert a date to GMT?
提问by coure2011
How to convert date of different timezones to GMT 0? Let say I have dates like this
如何将不同时区的日期转换为 GMT 0?假设我有这样的约会
Fri Jan 20 2012 11:51:36 GMT-0500
Fri Jan 20 2012 11:51:36 GMT-0300
Fri Jan 20 2012 11:51:36 GMT+0500
to
到
Fri Jan 20 2012 06:51:36 GMT
Fri Jan 20 2012 08:51:36 GMT
Fri Jan 20 2012 16:51:36 GMT
these are dates I am getting via new Date().toString()
on different timezones. Is there any js method to detect timezone and convert accordingly?
这些是我new Date().toString()
在不同时区获得的日期。是否有任何 js 方法来检测时区并进行相应的转换?
EDIT: The second three dates are not the GMT converted times of the first three. For example, Fri Jan 20 2012 11:51:36 GMT-0500
in GMT is Fri Jan 20 2012 16:51:36 GMT
not Fri Jan 20 2012 06:51:36 GMT
. GMT-0500 is behind GMT, not ahead, so you have to add the offset to get GMT, not subtract it.
编辑:后三个日期不是前三个的 GMT 转换时间。例如,Fri Jan 20 2012 11:51:36 GMT-0500
在 GMT 中Fri Jan 20 2012 16:51:36 GMT
不是Fri Jan 20 2012 06:51:36 GMT
. GMT-0500 在 GMT 之后,而不是在 GMT 之前,因此您必须添加偏移量才能获得 GMT,而不是减去它。
回答by Jivings
[Update]
[更新]
Matt Johnsons answer is much better than this one was.
马特约翰逊的回答比这个好得多。
new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()
回答by Matt Johnson-Pint
You can simply use the toUTCString
(or toISOString
) methods of the date object.
您可以简单地使用日期对象的toUTCString
(或toISOString
) 方法。
Example:
例子:
new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()
// Output: "Fri, 20 Jan 2012 16:51:36 GMT"
If you prefer better control of the output format, consider using a library such as date-fnsor moment.js.
如果您更喜欢更好地控制输出格式,请考虑使用诸如date- fns或moment.js 之类的库。
Also, in your question, you've actually converted the time incorrectly. When an offset is shown in a timestamp string, it means that the date and time values in the string have alreadybeen adjusted from UTC by that value. To convert back to UTC, invert the sign before applying the offset.
另外,在您的问题中,您实际上错误地转换了时间。当在时间戳字符串显示的偏移,这意味着字符串中的日期和时间值都已经被从UTC通过该值进行调整。要转换回 UTC,请在应用偏移量之前反转符号。
11:51:36 -0300 == 14:51:36Z
回答by Joseph Myers
Although it looks logical, the accepted answer is incorrect because JavaScript dates don't work like that.
尽管看起来合乎逻辑,但接受的答案是不正确的,因为 JavaScript 日期不是这样工作的。
It's super important to note here that the numerical value of a date (i.e., new Date()-0
or Date.now()
) in JavaScript is always measured as millseconds since the epochwhich is a timezone-free quantity based on a precise exact instant in the history of the universe. You do not need to add or subtract anything to the numerical value returned from Date()
to convert the numerical value into a timezone, because the numerical value has no timezone. If it did have a timezone, everything else in JavaScript dates wouldn't work.
在这里需要特别注意的是,JavaScript 中日期(即new Date()-0
或Date.now()
)的数值始终以自纪元以来的毫秒为单位来衡量,这是一个基于宇宙历史中精确时刻的无时区量。您不需要对返回的数值添加或减去任何内容即可将数值Date()
转换为时区,因为该数值没有 timezone。如果它确实有时区,则 JavaScript 日期中的其他所有内容都将不起作用。
Timezones, leap years, leap seconds, and all of the other endlessly complicated adjustments to our local times and dates, are based on this consistent and unambiguous numerical value, not the other way around.
时区、闰年、闰秒以及对我们本地时间和日期的所有其他无休止的复杂调整,都是基于这个一致且明确的数值,而不是相反。
Here are examples of how the numerical value of a date (provided to the date constructor) is independent of timezone:
以下是日期的数值(提供给日期构造函数)如何独立于时区的示例:
In Central Standard Time:
中部标准时间:
new Date(0);
// Wed Dec 31 1969 18:00:00 GMT-0600 (CST)
In Anchorage, Alaska:
在阿拉斯加安克雷奇:
new Date(0);
// Wed Dec 31 1969 15:00:00 GMT-0900 (AHST)
In Paris, France:
在法国巴黎:
new Date(0);
// Thu Jan 01 1970 01:00:00 GMT+0100 (CET)
It is critical to observe that in ALL cases, based on the timezone-free epoch offset of zero milliseconds, the resulting time is identical. 1 am in Paris, France is the exact same moment as 3 pm the day before in Anchorage, Alaska, which is the exact same moment as 6 pm in Chicago, Illinois.
重要的是要观察到,在所有情况下,基于零毫秒的无时区纪元偏移,结果时间是相同的。法国巴黎的凌晨 1 点与阿拉斯加安克雷奇的前一天下午 3 点完全相同,这与伊利诺伊州芝加哥的下午 6 点完全相同。
For this reason, the accepted answer on this page is incorrect. Observe:
因此,此页面上接受的答案是不正确的。观察:
// Create a date.
date = new Date();
// Fri Jan 27 2017 18:16:35 GMT-0600 (CST)
// Observe the numerical value of the date.
date.valueOf();
// 1485562595732
// n.b. this value has no timezone and does not need one!!
// Observe the incorrectly "corrected" numerical date value.
date.valueOf() + date.getTimezoneOffset() * 60000;
// 1485584195732
// Try out the incorrectly "converted" date string.
new Date(date.valueOf() + date.getTimezoneOffset() * 60000);
// Sat Jan 28 2017 00:16:35 GMT-0600 (CST)
/* Not the correct result even within the same script!!!! */
If you have a date string in another timezone, no conversion to the resulting object created by new Date("date string")
is needed. Why? JavaScript's numerical value of that date will be the same regardless of its timezone. JavaScript automatically goes through amazingly complicated procedures to extract the original number of milliseconds since the epoch, no matter what the original timezone was.
如果你在另一个时区有一个日期字符串,通过创建的结果对象中没有转换new Date("date string")
需要。为什么?无论时区如何,该日期的 JavaScript 数值都将相同。无论原始时区是什么,JavaScript 都会自动通过极其复杂的过程来提取自纪元以来的原始毫秒数。
The bottom line is that plugging a textual date string x
into the new Date(x)
constructor will automatically convert from the original timezone, whatever that might be, into the timezone-free epoch milliseconds representation of time which is the same regardless of any timezone. In your actual application, you can choose to displaythe date in any timezone that you want, but do NOT add/subtract to the numerical value of the date in order to do so. All the conversion already happened at the instant the date object was created. The timezone isn't even there anymore, because the date object is instantiated using a precisely-defined and timezone-free sense of time.
最重要的是,将文本日期字符串x
插入new Date(x)
构造函数将自动从原始时区(无论可能是什么)转换为无时区的纪元毫秒表示时间,无论任何时区都是相同的。在您的实际应用程序中,您可以选择以您想要的任何时区显示日期,但不要为此添加/减去日期的数值。在创建日期对象的那一刻,所有的转换都已经发生了。时区甚至不再存在,因为日期对象是使用精确定义且不受时区限制的时间感来实例化的。
The timezone only begins to exist again when the user of your application is considered. The user does have a timezone, so you simply displaythat timezone to the user. But this also happens automatically.
当您的应用程序的用户被考虑时,时区才开始再次存在。用户确实有一个时区,因此您只需向用户显示该时区。但这也会自动发生。
Let's consider a couple of the dates in your original question:
让我们考虑一下原始问题中的几个日期:
date1 = new Date("Fri Jan 20 2012 11:51:36 GMT-0300");
// Fri Jan 20 2012 08:51:36 GMT-0600 (CST)
date2 = new Date("Fri Jan 20 2012 11:51:36 GMT-0300")
// Fri Jan 20 2012 08:51:36 GMT-0600 (CST)
The console already knows my timezone, and so it has automaticallyshown me what those times mean to me.
控制台已经知道我的时区,因此它会自动向我显示这些时间对我的意义。
And if you want to know the time in GMT/UTC representation, also no conversion is needed! You don't change the time at all. You simply display the UTC string of the time:
如果您想知道 GMT/UTC 表示的时间,也不需要转换!你根本不改变时间。您只需显示时间的 UTC 字符串:
date1.toUTCString();
// "Fri, 20 Jan 2012 14:51:36 GMT"
Code that is written to convert timezones numerically using the numerical value of a JavaScript date is almost guaranteed to fail. Timezones are way too complicated, and that's why JavaScript was designed so that you didn't need to.
编写用于使用 JavaScript 日期的数值转换时区的代码几乎肯定会失败。时区太复杂了,这就是为什么 JavaScript 被设计成你不需要这样做的原因。
回答by Tomasz Nurkiewicz
Simply use Date.getUTC*()
family of methods. On my computer (CET, UTC+01:00):
只需使用Date.getUTC*()
系列方法。在我的电脑上(欧洲中部时间,UTC+01:00):
new Date().toString()
//Fri Jan 20 2012 18:05:16 GMT+0100 (CET)
new Date().getHours()
//18
new Date().getUTCHours()
//17
Notice that getUTCHours()
returns correct hour in UTC.
请注意,getUTCHours()
在 UTC中返回正确的小时。
See also:
也可以看看:
回答by code_love
I was just working on this, I may be a bit late, but I did a workaround. Here are steps: - Get current time from whatever timezone the app is fired.- - Get time zone offset of that zone from gmt 0. then add your timezone value in miliseconds. You will get the date in your time zone. I added some extra code to remove anything after the actual time.
我只是在研究这个,我可能有点晚了,但我做了一个解决方法。以下是步骤: - 从应用程序被触发的任何时区获取当前时间。- - 从 gmt 0 获取该区域的时区偏移量。然后添加您的时区值(以毫秒为单位)。您将获得您所在时区的日期。我添加了一些额外的代码以在实际时间之后删除任何内容。
getCurrentDate() {
var date = new Date();
var newDate = new Date(8 * 60 * 60000 + date.valueOf() +
(date.getTimezoneOffset() * 60000));
var ampm = newDate.getHours() < 12 ? ' AM' : ' PM';
var strDate = newDate + '';
return (strDate).substring(0, strDate.indexOf(' GMT')) + ampm
}
回答by Black Mamba
Based on the accepted answer and the second highest scoring answer both are not perfect according to the comment so I mixed both to get something perfect:
根据接受的答案和得分第二高的答案,根据评论都不完美,所以我将两者混合以获得完美的结果:
var date = new Date(); //Current timestamp
date = date.toGMTString();
//Based on the time zone where the date was created
console.log(date);
/*based on the comment getTimezoneOffset returns an offset based
on the date it is called on, and the time zone of the computer the code is
running on. It does not supply the offset passed in when constructing a
date from a string. */
date = new Date(date); //will convert to present timestamp offset
date = new Date(date.getTime() + (date.getTimezoneOffset() * 60 * 1000));
console.log(date);
回答by user3048405
GMTDate = new Date().toGMTString();
GMTDate = new Date().toGMTString();
回答by Hashmat Ali
After searching for an hour or two ,I've found a simple solution below.
搜索了一两个小时后,我在下面找到了一个简单的解决方案。
const date = new Date(`${date from client} GMT`);
inside double ticks, there is a date from client side plust GMT.
在双刻度内,有来自客户端的日期加上 GMT。
I'm first time commenting, constructive criticism will be welcomed.
我是第一次评论,欢迎有建设性的批评。
回答by Hashmat Ali
After searching for an hour or two ,I've found a simple solution below.
搜索了一两个小时后,我在下面找到了一个简单的解决方案。
const date = new Date(`${date from client} GMT`);
inside double ticks, there is a date from client side plust GMT.
在双刻度内,有来自客户端的日期加上 GMT。
I'm first time commenting, constructive criticism will be welcomed.
我是第一次评论,欢迎有建设性的批评。
回答by Maddy
I am trying with the below. This seems to be working fine. Are there any limitations to this approach? Please confirm.
我正在尝试以下。这似乎工作正常。这种方法有什么限制吗?请确认。
var now=new Date(); // Sun Apr 02 2017 2:00:00 GMT+1000 (AEST)
var gmtRe = /GMT([\-\+]?\d{4})/;
var tz = gmtRe.exec(now)[1]; // +1000
var hour=tz/100; // 10
var min=tz%100; // 0
now.setHours(now.getHours()-hour);
now.setMinutes(now.getMinutes()-min); // Sat Apr 01 2017 16:00:00 GMT