I'm having the same problem in 2025, but I need a solution that works without an external library. As my problem is related to <input type="date" />
(see my update of https://stackoverflow.com/a/79654183/15910996) and people use my webpage in different countries, I also need a solution that works automatically with the current user's locale.
My idea is to take advantage of new Date().toLocaleDateString()
always being able to do the right thing but in the wrong direction. If I take a static ISO-date (e.g. "2021-02-01") I can easily ask JavaScript how this date is formatted locally, right now. To construct the right ISO-date from any local date, I only need to understand in which order month, year and date are used. I will find the positions by looking at the formatted string from the static date.
Luckily, we don't have to care about leeding zeros and the kind of separators that are used in the locale date-strings.
With my solution, on an Australian computer, you can do the following:
alert(new Date(parseLocaleDateString("21/11/1968")));
In the US it will look and work the same like this, depending on the user's locale:
alert(new Date(parseLocaleDateString("11/21/1968")));
Please note: My sandbox-example starts with an ISO-date, because I don't know which locale the current user has... 😉
// easy:
const localeDate = new Date("1968-11-21").toLocaleDateString();
// hard:
const isoDate = parseLocaleDateString(localeDate);
console.log("locale:", localeDate);
console.log("ISO: ", isoDate);
function parseLocaleDateString(value) {
// e.g. value = "21/11/1968"
if (!value) {
return "";
}
const valueParts = value.split(/\D/).map(s => parseInt(s)); // e.g. [21, 11, 1968]
if (valueParts.length !== 3) {
return "";
}
const staticDate = new Date(2021, 1, 1).toLocaleDateString(); // e.g. "01/02/2021"
const staticParts = staticDate.split(/\D/).map(s => parseInt(s)); // e.g. [1, 2, 2021]
const year = String(valueParts[staticParts.indexOf(2021)]); // e.g. "1968"
const month = String(valueParts[staticParts.indexOf(2)]); // e.g. "11"
const day = String(valueParts[staticParts.indexOf(1)]); // e.g. "21"
return [year.padStart(4, "0"), month.padStart(2, "0"), day.padStart(2, "0")].join("-");
}