HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Check if a value is a valid JavaScript date

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptdatecheckvaluevalid

Problem

JavaScript provides a Date object that represents a single moment in time. It can be created using various formats, such as a string, an array of values, or individual values for the year, month, day, etc. However, not all values can be used to create a valid Date object.
So, how can you check if a value or set of values can be used to create a valid Date object? The simplest way is to use the Date() constructor with any value we want to check. Then, using Date.prototype.valueOf() and Number.isNaN(), we can determine if a valid Date object can be created.
In order to create a robust method, we can use the spread operator (...) to pass the values to the Date() constructor. This way, we can check if a valid Date object can be created from any number of values (e.g. a single string, a set of numeric values etc.).

Solution

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid('December 17, 1995 03:24:00'); // true
isDateValid('1995-12-17T03:24:00'); // true
isDateValid('1995-12-17 T03:24:00'); // false
isDateValid('Duck'); // false
isDateValid(1995, 11, 17); // true
isDateValid(1995, 11, 17, 'Duck'); // false
isDateValid({}); // false


In order to create a robust method, we can use the spread operator (...) to pass the values to the Date() constructor. This way, we can check if a valid Date object can be created from any number of values (e.g. a single string, a set of numeric values etc.).

Code Snippets

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid('December 17, 1995 03:24:00'); // true
isDateValid('1995-12-17T03:24:00'); // true
isDateValid('1995-12-17 T03:24:00'); // false
isDateValid('Duck'); // false
isDateValid(1995, 11, 17); // true
isDateValid(1995, 11, 17, 'Duck'); // false
isDateValid({}); // false

Context

From 30-seconds-of-code: is-date-valid

Revisions (0)

No revisions yet.