moment-timezone setDefault not behaving as expected

那年仲夏 提交于 2021-01-29 04:48:08

问题


Using the following code:

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

I get the following result:

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

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

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?


回答1:


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):

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

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

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>


来源:https://stackoverflow.com/questions/56098451/moment-timezone-setdefault-not-behaving-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!