Wrong date with javascript function toLocaleDateString()

Question

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!


Show source
| javascript   | date   | string   | locale   2017-01-02 21:01 2 Answers

Answers ( 2 )

  1. 2017-01-02 21:01

    Works for me with french Language first. It seems the language settings of your browser affects the results in a strange manner. Check your browser language settings.

  2. 2017-01-02 21:01

    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);
    
◀ Go back