JS: new Date() is not accepting date string in my own locale (d/m/y)
The Date object is very weak. You cannot tell it what format to expect. You can create it with a string in m/d/y like you stated, or new Date(year, month, day[, hours, seconds, milliseconds]);
It's pretty simple to convert your date string to a format that will give the expected result ('yyyy/mm/dd' or 'yyyy-mm-dd'):
new Date("21/11/1968".split('/').reverse().join('/'));
[edit] You may like this more generic method (part of the npm PureHelpers library):
document.querySelector("#result").textContent = `
tryParseDate("2017/03/22", "ymd"); // ${tryParseDate("2017/03/22", "ymd")}
tryParseDate("03/22/2017", "mdy"); // ${tryParseDate("03/22/2017", "mdy")}
tryParseDate("22-03-2017", "dmy"); // ${tryParseDate("22-03-2017", "dmy")}
`;
function tryParseDate(dateStringCandidateValue, format = "dmy") {
if (!dateStringCandidateValue) {
return null;
}
const mapFormat = format.split("").reduce(function(a, b, i) {
a[b] = i;
return a;
}, {});
const dateStr2Array = dateStringCandidateValue.split(/[ :\-\/]/g);
const datePart = dateStr2Array.slice(0, 3);
const datePartFormatted = [
+datePart[mapFormat.y],
+datePart[mapFormat.m] - 1,
+datePart[mapFormat.d]
];
if (dateStr2Array.length > 3) {
dateStr2Array.slice(3).forEach(t => datePartFormatted.push(+t));
}
const dateTrial = new Date(Date.UTC.apply(null, datePartFormatted));
return dateTrial && dateTrial.getFullYear() === datePartFormatted[0] &&
dateTrial.getMonth() === datePartFormatted[1] &&
dateTrial.getDate() === datePartFormatted[2]
? dateTrial
: null;
}
<pre id="result"></pre>