Pergunta

I've created a node.js app that takes some data from a remote database and handles it. Some of that data are Date objects. When I query the remote database from my local station at home, assuming that the data in the database is { dateOfEvent: "2014-04-13T00:00:00.000Z" }, the response I'm getting is { dateOfEvent: "2014-04-12T21:00:00.000Z" }, corresponding to the utc offset of my tymezone. If I make the same request from the cloud machine where my app is hosted, the response it gets is { dateOfEvent: "2014-04-13T04:00:00.000Z" } corresponding with its GMT-4 timezone.

Does node make some automatic datetime conversion or maybe the mysql driver for node?

Foi útil?

Solução

I ran into the same problem. It looks like the mysql module for node.js just takes whatever datetime string MySQL returns and IGNORES the timezone information that may be present (e.g. often a Z comes along for "Zulu time"). The resulting timezone free datetime string appears to be then given to a Date() constructor and returned to you as a LOCAL datetime.

That is if your DB stores dates in UTC timezone, a node.js MySQL query would return for example "2013-09-08T21:39:31.000Z". Now, if your local machine that made the query was in a GMT+7 timezone, then node.js and the mysql modules would take that date string to be IN LOCAL timezone and would call Date("2013-09-08T21:39:31.000 GMT-0700") on that string producing "2013-09-09T04:39:31 UTC"...

You can correct for that in your local TZ code by moving all datetimes that you receive from MySQL by as much back as your local time is from UTC. (e.g. if you are in GMT-7) you have to move all MySQL dates by 7 hours back (assuming again that your MySQL DB is in UTC timezone).

...
var tz_offset = (new Date()).getTimezoneOffset() * 60 * 1000; // get TZ offset in milliseconds
var corrected_datetime = new Date(mysql_datetime.getTime() - tz_offset); // now corrected

Hope this helps

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top