Search code examples
node.jsmongodbdatedatetimestrongloop

MongoDB ISODate and timezones on Node API


I built an API using Node, with the IBM Strongloop framework along with a MongoDB database. I have a problem with date timezones. On the frontend, I have a react datepicker that creates date objects.

I am in France, so GMT+1. If I create a date of birth for January 6th, 2000 on the frontend, the XHR request will send "2000-01-05T23:00:00.000Z" to the API.

If I try new Date('2000-01-05T23:00:00.000Z') on the frontend, I get the correct date Thu Jan 06 2000 00:00:00 GMT+0100 (CET)

On the API server, which is at timezone GMT+0, if I check the database I can see it as ISODate("2000-01-05T23:00:00Z")

If I try new Date('2000-01-05T23:00:00Z') on the server, I get the wrong date Wed Jan 05 2000 23:00:00 GMT+0000 (UTC)

Of course my users can have different timezones so setting the server timezone to GMT+1 won't solve the problem.

What is the correct solution ? Send dates to the server as strings, without timezone, and let it build them as dates before inserting ? Or is there another way ?


Solution

  • For "date only" data that need to be stored, I think it is 'easier' to break the dateTime into only years, month and day. You transmit this information to your server, and create a new UTC DateTime object based on the year, month and date, stored server-side. Or simply store the 3 fields separately.

    To get back this information you can use the getUTCxxx() (xxx being day, month or year) Javascript methods.

    Or you can create a new UTC dateTime with correct date front-side and send it the back-end, your pick.

    If you do that, you will have the correct date stored in the backend (like if it was correct-date at midnight UTC) .

    And then, when you query the value for display on the Front-end, you can force to take into account only the (UTC) date part of your datetime data, which are the correct year, month and day.

    Also, for Javascript I strongly recommend to use some external "proper" frameworks to handle date and time, like momentJS if you can.