如何将Moment.js日期转换为用户本地时区? [英] How to convert Moment.js date to users local timezone?
问题描述
我使用Moment.js和Moment-Timezone框架,并且具有明确在UTC时区中的Moment.js日期对象。如何将其转换为浏览器的当前时区?
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 = ???
所以如果我能找出用户本地时区,或者我想将日期对象转换为仅使用本地时区的另一个数据对象,无论实际是什么。
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和本地时区的完整功能。
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...
请注意,通过传递 testDateUtc
,这是一个时刻
对象,回到 moment()
构造函数,它创建一个克隆。否则,当您调用 .local()
时,它也会更改 testDateUtc
值,而不是 localDate
值。
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.
另请注意,如果您的原始输入包含时区偏移量,例如 +00:00
或 Z
,那么您可以直接用时刻
解析。您不需要使用 .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");
这篇关于如何将Moment.js日期转换为用户本地时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!