Data gets wrong when converting to Date in Javascript

Asked

Viewed 1,058 times

4

Hello, I have an API in . net that returns the data, the date comes in format: 2016-06-17T00:00:00 and I try to convert it to date in Javascript, so I do the following:

 var data = new Date(2016-06-17T00:00:00);

It works, but the date is different in the variable, it always changes the day. What I would have to do for the conversion to occur normally?

It does not always happen, for example in the case below occurs: API date: 2015-07-25T00:00:00

var data = new Date('2015-07-25T00:00:00');

The date is as follows: Fri Jul 24 2015 21:00:00 GMT-0300 (Official Time in Brazil), the day is amended.

But in the next example it does not occur: Date of API: 2016-06-24T09:23:53 After converting using the same code the date is the same: Fri Jun 24 2016 06:23:53 GMT-0300 (Brazil’s official time)

1 answer

2


Hello,

That’s right, js considers that the string you are passing as a parameter is in UTC format (because it does not have the time zone in the string), so when it converts to Date it considers its time zone, in the GMT-3 case so it subtracts 3 hours from the string time.

One way to avoid this would be to have your API return the time zone in the string, something like this: '2015-07-25T00:00:00-0300'

  • 1

    It is important to say that the time zone is NOT a constant, javascript takes the user’s browser time zone, so the time zone varies from region and period of the year. For example, here my time zone is in GMT-3 (Brasília Standard Time), but when the daylight saving time will be GMT-2 (Brasilia Daylight Saving Time). Therefore, the solution new Date('2015-07-25T00:00:00-0300') will fail when (or if) the Browser Time Zone changes. To resolve, the date can be saved in GMT+0 in the database, or saved along with your time zone to use it when instantiating Date.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.