将 UTC 日期时间转换为本地日期时间
我从服务器得到一个日期时间变量,格式如下:6/29/2011 4:52:48 PM
,它是 UTC 时间.我想使用 JavaScript 将其转换为当前用户的浏览器时区.
From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM
and it is in UTC time. I want to convert it to the current user’s browser time zone using JavaScript.
如何使用 JavaScript 或 jQuery 做到这一点?
How this can be done using JavaScript or jQuery?
推荐答案
在我看来,服务器在一般情况下应始终以标准化 ISO 8601 格式返回日期时间.
In my point of view servers should always in the general case return a datetime in the standardized ISO 8601-format.
更多信息在这里:
- http://www.w3.org/TR/NOTE-datetime
- https://en.wikipedia.org/wiki/ISO_8601
在这种情况下,服务器将返回 '2011-06-29T16:52:48.000Z'
,这将直接输入 JS Date 对象.
IN this case the server would return '2011-06-29T16:52:48.000Z'
which would feed directly into the JS Date object.
var utcDate = '2011-06-29T16:52:48.000Z'; // ISO-8601 formatted date returned from server
var localDate = new Date(utcDate);
localDate
将是正确的本地时间,在我的情况下是两个小时后(DK 时间).
The localDate
will be in the right local time which in my case would be two hours later (DK time).
您真的不必进行所有这些只会使事情复杂化的解析,只要您与服务器期望的格式一致.
You really don't have to do all this parsing which just complicates stuff, as long as you are consistent with what format to expect from the server.
相关文章