-1

I have an incoming json like:

...
"orderId": 34363231,\
"plannedPalletPls": 0,\
"shipmentId": 11737,\
"createdAt": "2022-10-07T13:57:01.13Z",\
"updatedAt": "2022-10-07T13:57:01.13Z",\
...

For every key I need to check if it is a date or not. I use this code:

if (!isNaN(Date.parse(value))) {...}

But, for example, for value 11737 this expression returns true. And it is not what I need. What is a good way to check if the value is real date?

Vlad Aleshin
  • 361
  • 4
  • 15
  • 2
    Define "a valid date"? Is 01/12/2023 valid? What about 12/01/2023? What about chinese dates? etc. etc. – Liam Feb 22 '23 at 09:25
  • 1
    @Konrad—that statement is totally wrong. [*Date.parse*](https://262.ecma-international.org/#sec-date.parse) returns a number, which might be *NaN*. It never returns a *Date*. – RobG Feb 22 '23 at 10:37

1 Answers1

0

"11737" is considered a valid date string by some JS engines (Chrome) and not valid by others (FF). You should not rely on the parse algorithm that is implementation dependent unless the string follows formats that are specified in the ECMAScript specification.

If your JSON is always going to use that ISO format for dates, then use a regular expression to identify such strings first:

const value = "2022-10-07T13:57:01.13Z";

const valueAsDate = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d+Z$/.test(value) && new Date(value);

console.log(valueAsDate);

This will avoid the false positives you get.

trincot
  • 317,000
  • 35
  • 244
  • 286