I have a table of data that needs to be sorted and in order to do so, I have to determine the datatype of the columns: numeric, text, or date. And no, I never know what the datatype of column will be and it will always have different data. I have to extrapolate the datatype by looking at the textcontent of the cell. The one I’m having an issue with is the date.
new Date("MOD-001-01") actually returns a real date of 1/1/2001.
new Date("This is not a date 1") also returns a real date, again 1/1/2001.
Is there any way to reliably test a value to see if its a date?
2
Answers
Creating a date object by using the method referenced:
new Date()
accepts valid date string variations by parsing the string for numeric values, so in your example is essentially using the value 1 as the date.This will happen as long as there is at least one number. Using methods such as
Date.parse()
as mentioned in another comment will also give you unix value based on the parsed numeric value.An effective method of checking for valid dates would by using a regex expression on the string.
There are various effective solutions here -> Regex to validate date formats
To reliably test if a value is a date in JavaScript, you can use the
Date.parse()
method. TheDate.parse()
method attempts to parse a date string and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. If the date string is not valid, it will returnNaN
.You can use the following function to check if a value is a valid date:
Now you can use the
isDate()
function to check if a value is a date. It will returntrue
if the value is a valid date, andfalse
otherwise.Here are some examples:
By using
Date.parse()
, you can reliably determine if a value is a date or not.or else
You can use a regular expression to check if a value is a date.
You can use a library like Moment.js to parse and manipulate dates. These libraries provide more robust date parsing and manipulation capabilities than the built-in Date object.
pls upvote if you find this helpful