时刻时区 setDefault 未按预期运行 [英] moment-timezone setDefault not behaving as expected

查看:69
本文介绍了时刻时区 setDefault 未按预期运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码:

console.log(moment().toJSON());
moment.tz.setDefault("Europe/Brussels");
console.log(moment().toJSON());

我得到以下结果:

2019-05-12T10:39:12.851Z
2019-05-12T10:39:12.863Z

但是,当我阅读 moment-timezone 的文档时,setDefault 应该将我的默认时区设置为欧洲/布鲁塞尔",因此输出应该是:

However, when I read the documentation of moment-timezone, setDefault is supposed to set my default timezone on "Europe/Brussels", so the output should be:

2019-05-12T10:39:12.851Z
2019-05-12T11:39:12.863Z

显然,setDefault 不能用于我想要的(它生成一个新日期,就像我在指定的时区一样),那么这样做的最佳选择是什么?

Apparently, setDefault cannot be used to what I want (which is generating a new date as if I were in the specified timezone), so what would be the best option to do so?

推荐答案

setDefault 按预期工作,问题在于您显示矩实例值的方式.toJSON() 显示 UTC 时间(另见toISOString():.toISOString() 返回一个 UTC 时间戳):

setDefault works as expected, the issue is the way you are displaying the value of moment instances. toJSON() shows time for UTC (See also toISOString(): .toISOString() returns a timestamp in UTC):

在将对象序列化为 JSON 时,如果存在 Moment 对象,则将其表示为 ISO8601 字符串,调整为 UTC.

When serializing an object to JSON, if there is a Moment object, it will be represented as an ISO8601 string, adjusted to UTC.

如果你想要一个反映时刻utcOffset()的ISO8601字符串,那么你可以像这样修改toJSON函数:

If instead you would like an ISO8601 string that reflects the moment's utcOffset(), then you can modify the toJSON function like this:

moment.fn.toJSON = function() { return this.format(); }

所以你可以使用 format()相反,这里有一个实时示例:

So you can use format() instead, here a live sample:

console.log(moment().toJSON());
console.log(moment().format());
moment.tz.setDefault("Europe/Brussels");
console.log(moment().toJSON());
console.log(moment().format());

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>

这篇关于时刻时区 setDefault 未按预期运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆