date.toLocaleDateString() returns date without zeros even if locale is provided
string - Wrong date with javascript function toLocaleDateString() - Stack Overflow
javascript - Jquery new Date - Convert to yyyy-MM-dd and use toLocaleDateString - Stack Overflow
toLocaleDateString won't equal the same string
An executable sample:
(function(){
let dtArrivee = new Date("2018-11-13");
let strArrivee = "";
let options = { year: 'numeric', month: 'numeric', day: 'numeric' };
strArrivee = dtArrivee.toLocaleDateString("fr-CA", options);
return strArrivee == "2018-11-13";
})();
// => trueWorks for me in Firefox as well, but I can reproduce your issue in Edge...
More on reddit.comOn 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
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);
Try using fr-CA that returns the format in yyyy-MM-dd.
var yyyymmdd = (new Date ()).toLocaleDateString ("fr-CA");
console.log (yyyymmdd);
If you need the local date (GMT+10 in your case), you need to use methods of Date:
function toHtmlDate (d) {
return (d.getFullYear() + '-0' + (d.getMonth() + 1) + '-0' + d.getDate()).replace(/-0(\d\d)/g, '-$1');
}
If you need an ISO date (GMT), you can use new Date().toISOString().substring(0, 10). For explanation:
Date.prototype.toLocaleDateStringoutput depends on your locale, using string splitting on it might not work for another userDate.prototype.toISOStringalways returns####-##-##T##:##:##.###<timezone>, for example2015-10-18T23:23:22.880Z. Take the first 10 characters, you have<year>-<month>-<date>.