gpt4 book ai didi

javascript - Moment js默认时区在创建日期时不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:40:18 26 4
gpt4 key购买 nike

请引用以下代码片段。

问题 1: 我正在为 moment 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() 函数,但在从 moment 创建新日期对象时不应用。

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。解决方案: Moment timezone 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>

关于javascript - Moment js默认时区在创建日期时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47303375/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com