Moment JS默认时区在创建日期时不起作用

Syed Aqeel Ashiq

请参考以下代码段。

问题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.解决方案:时区setDefault会影响setDefault之后创建的实例。如果您这样调试:

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());
<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>

您可以看到setDefault正在运行。

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

console.log(moment(new Date()).format());
moment.tz.setDefault("America/Lima");
console.log(moment(new Date()).local().format());
console.log(moment(new Date()).format());
<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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章