問題描述
我使用 Moment.js 和 Moment-Timezone 框架,并且有一個(gè) Moment.js 日期對(duì)象,該對(duì)象明確使用 UTC 時(shí)區(qū).如何將其轉(zhuǎn)換為瀏覽器的當(dāng)前時(shí)區(qū)?
I use the Moment.js and Moment-Timezone frameworks, and have a Moment.js date object which is explicitly in UTC timezone. How can I convert that to the current timezone of the browser?
var testDateUtc = moment.tz("2015-01-30 10:00:00", "UTC");var localDate = ???
所以如果我能找出用戶的本地時(shí)區(qū)就好了;或者,我想將日期對(duì)象轉(zhuǎn)換為另一個(gè)只使用本地時(shí)區(qū)"的數(shù)據(jù)對(duì)象,無論它實(shí)際上是什么.
So it would be fine if I could find out the users local time zone; or alternatively I'd like to convert the date object into another data object which just uses the "local timezone", no matter what that actually is.
推薦答案
您不需要為此使用 moment-timezone.主要的 moment.js 庫具有使用 UTC 和本地時(shí)區(qū)的完整功能.
You do not need to use moment-timezone for this. The main moment.js library has full functionality for working with UTC and the local time zone.
var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).local();
從那里您可以使用您可能期望的任何功能:
From there you can use any of the functions you might expect:
var s = localDate.format("YYYY-MM-DD HH:mm:ss");
var d = localDate.toDate();
// etc...
請(qǐng)注意,通過將 testDateUtc
(它是一個(gè) moment
對(duì)象)傳回 moment()
構(gòu)造函數(shù),它會(huì)創(chuàng)建一個(gè) 克隆.否則,當(dāng)您調(diào)用 .local()
時(shí),它也會(huì)更改 testDateUtc
值,而不僅僅是 localDate
值.時(shí)刻是可變的.
Note that by passing testDateUtc
, which is a moment
object, back into the moment()
constructor, it creates a clone. Otherwise, when you called .local()
, it would also change the testDateUtc
value, instead of just the localDate
value. Moments are mutable.
另外請(qǐng)注意,如果您的原始輸入包含時(shí)區(qū)偏移量,例如 +00:00
或 Z
,那么您可以直接使用 moment 解析它代碼>.您不需要使用
.utc
或 .local
.例如:
Also note that if your original input contains a time zone offset such as +00:00
or Z
, then you can just parse it directly with moment
. You don't need to use .utc
or .local
. For example:
var localDate = moment("2015-01-30T10:00:00Z");
這篇關(guān)于如何將 Moment.js 日期轉(zhuǎn)換為用戶本地時(shí)區(qū)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!