-1

I want to validate that a date can comply with multiple formats like the following dates:

const dates=
["02/01/2021", // DD/MM/YYYYY
"02/2021/01",  // MM/YYYY/DD
"2021/02/01",  // YYYY/MM/DD
"02-01-2021",  // DD-MM-YYYYY
"02-2021-01",  // MM-DD-YYYY
"2021-02-01",  // YYYY-MM-DD
"02012021",    // DDMMYYYYY
"02202101",    // MMDDYYYYY
"20210201",    // YYYYYMMDD


"122344"];     // Wrong format

I am using date-fns to do it, but currently in this live code, I am not getting the expected result. I need all dates to be valid except the last one, how can I do it?

live code:

https://codesandbox.io/s/date-fns-example-forked-4p346k?file=/src/index.js:23-724

import "./styles.css";

import {
  isValid,
  parseISO
} from "date-fns";

const dates=
["02/01/2021", // DD/MM/YYYYY
"02/2021/01",  // MM/YYYY/DD
"2021/02/01",  // YYYY/MM/DD
"02-01-2021",  // DD-MM-YYYYY
"02-2021-01",  // MM-DD-YYYY
"2021-02-01",  // YYYY-MM-DD
"02012021",    // DDMMYYYYY
"02202101",    // MMDDYYYYY
"20210201",    // YYYYYMMDD
"122344"];     // Wrong format
dates.forEach((date)=>{
  console.log(date, isValid(parseISO(date)));
});
yavgz
  • 275
  • 3
  • 17
  • What you're asking **is impossible** due to ambiguity: without further context you have no way of knowing if `2023-02-01` is February 1st - or the 2nd of January. Besides, [**no-one** uses `YDM` (`yyyy-dd-MM`) as a date-format](https://en.wikipedia.org/wiki/Date_format_by_country). Just stick to [ISO 8601 and/or RFC 3339](https://stackoverflow.com/questions/522251/whats-the-difference-between-iso-8601-and-rfc-3339-date-formats) and _known_ regional formats. – Dai Aug 09 '23 at 01:57

0 Answers0