1

I want to check string value is Date or not ? I use the following code but dose not work:

const date = "2019-12-31T20:30:00+00:00";
if (date instanceof Date) {
    // date is Date....
}

or

if (Object.prototype.toString.call(date) === '[object Date]') {
  // date is Date....
}
reymon359
  • 1,240
  • 2
  • 11
  • 34

1 Answers1

-1

Your first condition is always true because of you are not converting string to Date. There is two way you can do this.

First, you can construct a Date object with given string and check whether Date is valid or not

const dateString = '2019-12-31T20:30:00+00:00';
const date = new Date(dateString);

if(date.toString() !== "Invalid Date") {
    // String is valid date.
} else {
    // String is not valid date.
}

The other way is, firstly you can check the given string is valid date and then consruct a Date object.

 const dateString = '2019-12-31T20:30:00+00:00';
 const parsed = Date.parse(dateString);

 if(!isNaN(parsed)) {
     // String is valid date.
     const date = new Date(parsed);
 } else {
     // String is not a valid date.
 }
aprogrammer
  • 1,764
  • 1
  • 10
  • 20
  • If I change the value of dateString to `"1"` it always returns true while It's not a valid date; –  Jun 13 '20 at 10:06
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Jun 13 '20 at 21:23