Skip to content

Commit 6057a53

Browse files
committed
add check if date is valid tutorial
1 parent 34a03df commit 6057a53

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/tutorials.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,14 @@ const moment = require('moment');
55
const axiosPath = require('./axiosPath');
66

77
const tutorials = [
8+
{
9+
title: 'Check if a Date is Valid in JavaScript',
10+
raw: './tutorials/fundamentals/check-if-date-is-valid.md',
11+
url: '/tutorials/fundamentals/check-if-date-is-valid',
12+
description: 'Got a JavaScript date that is showing up as "Invalid Date" in your console? Here\'s how you check for that.',
13+
tags: ['fundamentals'],
14+
date: moment('2023-08-14')
15+
},
816
{
917
title: 'Encode base64 in JavaScript',
1018
raw: './tutorials/fundamentals/encode-base64.md',
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

Comments
 (0)