Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong date with javascript function toLocaleDateString()

I use the javascript function of the Date class toLocaleDateString() in a project to get the proper formatting according to the user's locale, so simple. However, the day of the month is not always right (It is somethimes one day less than expected). I cannot seem to understand why this happens.

I built a jsfiddle to show the problem. It occurs with the month of october. The date should be 3 like in all the other months but somehow it's 2.

https://jsfiddle.net/vincepunkrock/nh1u3ord/

Here is the important part of code and the result (My locale is 'de'):

for(var i = 0; i < 12; i++)
{
    var d = new Date(1993,i,3);
    var n = d.toLocaleDateString();
    document.getElementById("demo").innerHTML += n + "<br>";
}

3.1.1993
3.2.1993
3.3.1993
3.4.1993
3.5.1993
3.6.1993
3.7.1993
3.8.1993
3.9.1993
2.10.1993
3.11.1993
3.12.1993

Do you guys have an idea about what's happening here and what can I do to solve it?

Thank you very much!

like image 715
Vincent Gagnon Avatar asked Aug 31 '26 03:08

Vincent Gagnon


2 Answers

On Firefox (60) this doesn't show up when initializing the date from numbers (my timezone is GMT-3: observe how the Date initializer adds 3 hours automatically):

>> var d;
>> d = new Date(2019,10,17);
Date 2019-11-17T03:00:00.000Z
>> console.log(d.toLocaleDateString('de'))
17.11.2019

However, when initializing it from a string, problems show up:

>> d = new Date("2019-10-17");
Date 2019-10-17T00:00:00.000Z
>> console.log(d.toLocaleDateString('de'))
16.11.2019

What I found out could solve the problem was manually specifying the timezone as UTC:

>> console.log(d.toLocaleDateString('de', {timeZone: "UTC"}))
17.10.2019
like image 81
Ronan Paixão Avatar answered Sep 01 '26 15:09

Ronan Paixão


I think Pointy nailed it with his comment. toLocalDateString is definitely factoring in DST with a presumed hour of 00:00:0000 since it's not being specified so the "fall back" hour goes into the prior day. I'm not sure what your locale is to have that only happen in one month but I'm not a pro on time zones. The script works perfectly for me.

Update: set the "time" in your new date to the middle of the day if this isn't the behavior you want.. then the Daylight savings time adjustment won't kick back and forth into different dates..

var d = new Date(1993,i,3, 12,30,30,30);
like image 31
pizzaslice Avatar answered Sep 01 '26 17:09

pizzaslice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!