Fixing MomentJS interpreting dates as local time
Problem:
You live in a non-UTC timezone. Dates parsed using MomentJS like
moment("2017-01-01")
are interpreted as local time as opposed to UTC (as would be appropiate based on the Z
in the ISO8601 timestamp) and therefore trying to format them yields an offset timestamp:
moment("2017-01-01").toDate().toISOString()
// "2016-12-31T23:00:00.000Z" <-- Offset by 1 hour (MEZ - UTC)
This causes you trouble as often the original date is not preserved: In the example above, the correct date would be 2017-01-01
but it is 2016-12-31
instead.
Solution 1: Force moment to parse the date as UTC
moment.utc("2017-01-01").toDate().toISOString()
// "2017-01-01T00:00:00.000Z" <-- Correct
Solution 2: Manually subtract the timezone offset
let m = moment("2017-01-01");
// Subtract the difference between timezone and UTC
m = m.subtract(m.toDate().getTimezoneOffset(), 'minutes');
// m.toDate().toISOString() === "2017-01-01T01:00:00.000Z" - CORRECT
Use this if Solution 1 does not work or you can’t modify the parsing code: This solution works even if the date has already been parsed.
DO NOT use
new Date().getTimezoneOffset() // NEVER USE THIS! MIGHT USE THE WRONG OFFSET!
because it uses the timezone offset of the current date instead of the date parsed by MomentJS. Obviously this is wrong in countries with summertime, since dates may have different offsets depending on the date. Moreover, in rare cases the client’s computer timezone may have changed due to travel etc in the meantime and might therefore might not represent the correct offset to use.