Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting an "invalid date" Date instance in JavaScript

I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:

var d = new Date("foo"); console.log(d.toString()); // shows 'Invalid Date' console.log(typeof d); // shows 'object' console.log(d instanceof Date); // shows 'true' 

Any ideas for writing an isValidDate function?

  • Ash recommended Date.parse for parsing date strings, which gives an authoritative way to check if the date string is valid.
  • What I would prefer, if possible, is have my API accept a Date instance and to be able to check/assert whether it's valid or not. Borgar's solution does that, but I need to test it across browsers. I also wonder whether there's a more elegant way.
  • Ash made me consider not having my API accept Date instances at all, this would be easiest to validate.
  • Borgar suggested testing for a Date instance, and then testing for the Date's time value. If the date is invalid, the time value is NaN. I checked with ECMA-262 and this behavior is in the standard, which is exactly what I'm looking for.
like image 463
orip Avatar asked Aug 30 '09 11:08

orip


People also ask

How do you check if a string is a valid date in JavaScript?

Using the Date. One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.

How do you check if it is date or not in JavaScript?

You can use the ! isNaN() function to check whether a date is valid. If x is a Date, isNaN(x) is equivalent to Number.

What does invalid date format mean?

Unclean or Invalid Dates (DMY Format) should be converted to valid data formats. By default, Excel accepts date input in MM/DD/YY format (US format) unless you change the control panel settings of your PC. Example 22.10. 2007 or 22/10/2007 date may be considered invalid.


1 Answers

Here's how I would do it:

if (Object.prototype.toString.call(d) === "[object Date]") {   // it is a date   if (isNaN(d)) { // d.getTime() or d.valueOf() will also work     // date object is not valid   } else {     // date object is valid   } } else {   // not a date object } 

Update [2018-05-31]: If you are not concerned with Date objects from other JS contexts (external windows, frames, or iframes), this simpler form may be preferred:

function isValidDate(d) {   return d instanceof Date && !isNaN(d); } 

Update [2021-02-01]: Please note that there is a fundamental difference between "invalid dates" (2013-13-32) and "invalid date objects" (new Date('foo')). This answer does not deal with validating date input, only if a Date instance is valid.

like image 57
Borgar Avatar answered Sep 21 '22 07:09

Borgar