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



请参考以下代码片段。

问题 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>

您可以看到设置默认正在工作。

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>

相关内容

  • 没有找到相关文章

最新更新