|
| 1 | +In JavaScript, a date is invalid if its `valueOf()` is [NaN](/tutorials/fundamentals/check-nan). |
| 2 | + |
| 3 | +```javascript |
| 4 | +const date = new Date(NaN); |
| 5 | +date.toString(); // 'Invalid Date' |
| 6 | +``` |
| 7 | + |
| 8 | +This is tricky because `date` still looks like a valid date: it is still `instanceof Date`, etc. |
| 9 | +One way to check for an "Invalid Date" is to check if the date's `valueOf()` is `NaN`: |
| 10 | + |
| 11 | +```javascript |
| 12 | +Number.isNaN(date.valueOf()); // true |
| 13 | + |
| 14 | +const validDate = new Date('2022-06-01'); |
| 15 | +Number.isNaN(validDate.valueOf()); // false |
| 16 | +``` |
| 17 | + |
| 18 | +## Debugging Why a Date is Invalid |
| 19 | + |
| 20 | +There are two common reasons for an "Invalid Date". |
| 21 | +The first is passing a value that JavaScript can't interpret as a date to the `new Date()` constructor as follows. |
| 22 | + |
| 23 | +```javascript |
| 24 | +const badDate = new Date('foobar'); |
| 25 | +badDate.valueOf(); // NaN |
| 26 | +badDate.toString(); // 'Invalid Date' |
| 27 | +``` |
| 28 | + |
| 29 | +Invalid date strings aren't the only potential cause: passing in a numeric calculation that adds up to `NaN` also causes "Invalid Date". |
| 30 | + |
| 31 | +```javascript |
| 32 | +const obj = {}; |
| 33 | + |
| 34 | +// 3 * obj.nonexistentProperty === undefined |
| 35 | +const badDate2 = new Date(3 * obj.nonexistentProperty); |
| 36 | +badDate2.valueOf(); // NaN |
| 37 | +badDate2.toString(); // 'Invalid Date' |
| 38 | +``` |
| 39 | + |
| 40 | +A valid date can become an invalid date due to date manipulation methods like `setDate()` and `setHours()`. For example: |
| 41 | + |
| 42 | +```javascript |
| 43 | +const obj = {}; |
| 44 | + |
| 45 | +const badDate3 = new Date('2023-06-01'); |
| 46 | +// 3 * obj.nonexistentProperty === undefined |
| 47 | +badDate3.setHours(3 * obj.nonexistentProperty); |
| 48 | +badDate3.valueOf(); // NaN |
| 49 | +badDate3.toString(); // 'Invalid Date' |
| 50 | +``` |
0 commit comments