I have a string, which can come in different formats:
01.01.2020
01/01/2020
01-01-2020
or
2020-01-01
2020.01.01
2020/01/01
Now if I try doing
const date = new Date(myDateString);
I will in some cases get an error "Invalid Date". How can I cover all scenarios and transform any scenario into a valid date?
It seems like the new Date(), only takes the format Y-m-y?, even though the other cases are also "valid" dates?
You can split the string on the known delimiters and then see whether the first part has four digits. If so, you know it's year-month-day. If not, you know it's month-day-year. You can then construct the date accordingly:
const dateStrings = [
"10.31.2020",
"10/31/2020",
"10-31-2020",
"2020-10-31",
"2020.10.31",
"2020/10/31",
]
function parseDateStr(str) {
// split on dots, dashes, and slashes
const parts = str.split(/[./-]/);
// mm-dd-yyyy
const [year, month, day] = parts[0].length > 2 ? parts : [parts[2], parts[0], parts[1]];
// alternate for dd-mm-yyyy
// const [year, month, day] = parts[0].length > 2 ? parts : parts.reverse();
// construct and return the date. (month is 0 based)
return new Date(year, month - 1, day);
}
const results = dateStrings.map(parseDateStr);
console.log(results);
You can moment to do that. But you need to know which format is used.
Date() constructor is accurate if it's parameters are YYYY, MM, DD. The dates of Jan 1, 2020 should go like this:
new Date(2020, 0, 1) // Month is 0 index, so MM -1
Given an array of strings .map() and split() each by .-/ delimitters, resulting in sub-arrays of 3 strings from each string:
strArr.map(str => str.split(/[-./]/))
then .flatMap() to catch any array that starts with 2 digits and .reverse() it:
.flatMap(sub => sub[0].length === 2 ? [sub.reverse()] : [sub])
Finally, .flatMap() each sub-array into the Date() constructor:
.flatMap(sub => [new Date(+sub[0], +sub[1] - 1, +sub[2])])
const jan1_2020 = [
`01.01.2020`,
`01/01/2020`,
`01-01-2020`,
`2020-01-01`,
`2020.01.01`,
`2020/01/01`
];
const formatDate = strArr => strArr.map(str => str.split(/[-./]/)).flatMap(sub => sub[0].length === 2 ? [sub.reverse()] : [sub]).flatMap(sub => [new Date(+sub[0], +sub[1] - 1, +sub[2])]);
let x = formatDate(jan1_2020);
console.log(x);