moment-timezone setDefault 未按预期运行
moment-timezone setDefault not behaving as expected
使用以下代码:
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
应该将我的默认时区设置为 "Europe/Brussels",因此输出应该是:
2019-05-12T10:39:12.851Z
2019-05-12T11:39:12.863Z
显然,setDefault
不能用于我想要的(生成新日期,就好像我在指定时区),那么最好的选择是什么?
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 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(); }
所以你可以使用 format()
来代替,这里是一个活生生的例子:
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>
使用以下代码:
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
应该将我的默认时区设置为 "Europe/Brussels",因此输出应该是:
2019-05-12T10:39:12.851Z
2019-05-12T11:39:12.863Z
显然,setDefault
不能用于我想要的(生成新日期,就好像我在指定时区),那么最好的选择是什么?
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 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 thetoJSON
function like this:moment.fn.toJSON = function() { return this.format(); }
所以你可以使用 format()
来代替,这里是一个活生生的例子:
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>