Daylight Saving Time date conversion

Asked

Viewed 900 times

6

Currently in my system I use the following code, to convert the dates coming in ajax. new Date(parseInt(data.replace(/\/Date\((-?\d+)\)\//, '$1')))

Where the variable data is a string that comes in format '/Date(1508551200000)/', so you can replace the variable with this string to test.

Now my problem began to appear on this date, because when I convert it with the code above gives the following result:

Fri Oct 20 2017 23:00:00 GMT-0300 (Official Time in Brazil)

But the real value is 21/10/2017, when doing a survey find that this date was the beginning of Daylight Saving Time 2017 and with that it decreased by 1hr, so I found that the dates in Daylight Saving Time are having this same problem

How can I make this conversion to q it ignore this and return me the value q I wish, without decreasing in 1hr, in case ignoring this daylight saving time conversion.

1 answer

2

Use the method toLocaleString() and then convert the result into Date object:

var data = '/Date(1508551200000)/';
data = new Date(parseInt(data.replace(/\/Date\((-?\d+)\)\//, '$1'))).toLocaleString('pt-BR', { timeZone: 'America/Sao_Paulo' });
var dt = data.substring(0, 10).split("/");
data = new Date(dt[2], dt[1] - 1, dt[0]);

console.log(data);

Jsfiddle => Sat Oct 21 2017 00:00:00 GMT-0300 (Official Time in Brazil)

  • 1

    It would not have as it gives me the result in the Date object, instead it is already formatted?

  • 1

    Besides .toLocaleString(), gives way that was passed, because if the person access the system in another zone will display divergent information

  • I will see here... but in case, would add . toLocaleString("en")

  • 2

    in the case only this would not be enough, would have to set Timezone tb, for example .toLocaleString('pt-BR', { timeZone: 'America/Sao_Paulo' });

  • That’s right. Look now.

Browser other questions tagged

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