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?
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 thetoJSON
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>