問題描述
我從服務(wù)器得到一個(gè)日期時(shí)間變量,格式如下:6/29/2011 4:52:48 PM
,它是 UTC 時(shí)間.我想使用 JavaScript 將其轉(zhuǎn)換為當(dāng)前用戶的瀏覽器時(shí)區(qū).
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 做到這一點(diǎn)?
How this can be done using JavaScript or jQuery?
推薦答案
在我看來,服務(wù)器在一般情況下應(yīng)始終以標(biāo)準(zhǔn)化 ISO 8601 格式返回日期時(shí)間.
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
在這種情況下,服務(wù)器將返回 '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
將是正確的本地時(shí)間,在我的情況下是兩個(gè)小時(shí)后(DK 時(shí)間).
The localDate
will be in the right local time which in my case would be two hours later (DK time).
您真的不必進(jìn)行所有這些只會(huì)使事情復(fù)雜化的解析,只要您與服務(wù)器期望的格式一致.
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.
這篇關(guān)于將 UTC 日期時(shí)間轉(zhuǎn)換為本地日期時(shí)間的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!