JavaScript, why is my local date suddenly UTC?

Claudia Minardi
NEXT Engineering
Published in
2 min readJan 6, 2016

Each time you think you understand date handling, there is something new waiting around the corner that will catch you off guard.

I faced this very recently. I passed a local date to a method — but what a surprise when I accessed the parameter in the method: the local date was magically — and wrongly — converted into UTC. Nothing in the code prompted an explicit conversion. How was this possible?

Like always, the issue was very frustrating to find but very trivial to solve. The date was passed as a string, lacking information on the timezone, and converted using JavaScript’s native method:

Date.parse(“2015–10–12 12:00:00”)

As the documentation states, JavaScript’s native function to parse dates from a string is quite unreliable: As a general rule, in absence of a timezone indication it parses the date as UTC, returning the number of milliseconds since January 1, 1970. And that’s not all! Across different ECMAScript implementations strings like 2015–10–12 12:00:00 may be parsed to as NaN, UTC or local timezone.

Thankfully, Moment.js came to the rescue! It recognizes standard formats for local dates and parses them correctly. In our case it parses the string as local date, since no timezone or offset was provided:

// Returns local date with correct timezone offset
moment(“2015–10–12 12:00:00”).toDate()

Happy coding!

Photo: Unsplash

--

--