创建日期时,时刻js默认时区不起作用

时间:2017-11-15 09:13:10

标签: javascript angular timezone momentjs

请参阅以下代码段。

问题1:我正在为时刻js设置默认时区。但是在设置之后,如果我从一刻开始检索时区,那就不是我刚设置的时区。

console.log("Currrent timezone: "); console.log(moment.tz());
console.log("Updating timezone: "); console.log("America/Lima");
moment.tz.setDefault("America/Lima");
console.log("Currrent timezone after updating: "); console.log(moment.tz());

打印以下日志:

Currrent timezone: Moment {_isAMomentObject: true, _isUTC: true, _pf: {…}, _locale: Locale, _d: Wed Nov 15 2017 13:39:45 GMT+0500 (Pakistan Standard Time), …}
Updating timezone: America/Lima
Currrent timezone after updating: Moment {_isAMomentObject: true, _isUTC: true, _pf: {…}, _locale: Locale, _d: Wed Nov 15 2017 13:39:45 GMT+0500 (Pakistan Standard Time), …}

问题2:另外一个问题是,我设置的默认时区应用于moment.format()函数,但从当前创建新日期对象时未应用。

console.log(moment(new Date()).toDate()); // this uses user browser timezone
// prints Wed Nov 15 2017 13:57:40 GMT+0500 (Pakistan Standard Time)
// I want it to give the time in the timezone which i just set above

console.log(moment(new Date()).local().toDate());
// prints Wed Nov 15 2017 13:57:40 GMT+0500 (Pakistan Standard Time)

console.log(moment(new Date()).format()); // this uses the timezone which I set above in moment default timezone. This is correct intended behavior
// prints: 2017-11-15T03:57:40-05:00

1 个答案:

答案 0 :(得分:6)

<强> 1。解决方案:时刻timezone setDefault正在影响setDefault之后创建的实例。如果你这样调试:

&#13;
&#13;
console.log("Currrent timezone: "); console.log(moment().tz());
console.log("Current time: "); console.log(moment().format());
console.log("Updating timezone: "); console.log("America/Lima");
moment.tz.setDefault("America/Lima");
console.log("Current time: "); console.log(moment().format());
console.log("Currrent timezone after updating: "); console.log(moment().tz());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

您可以看到setDefault正在运行。

<强> 2。解决方案: .local()函数在原始时刻设置一个标记,使用当地时间显示片刻而不是原始片刻的时间。即使您使用moment.tz.setDefault来更改时区,它也会获得计算机的时区。

&#13;
&#13;
console.log(moment(new Date()).format());
moment.tz.setDefault("America/Lima");
console.log(moment(new Date()).local().format());
console.log(moment(new Date()).format());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;