Home > Article > Web Front-end > How to determine if it is a date in JavaScript
In JavaScript, you can use the isNaN() method and the parse() method of the Date object to determine whether it is a date. The parse() method can parse a date and time string; the syntax "if(isNaN(data) &&!isNaN(Date.parse(data)))”.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In JavaScript, you can use the parse() method and isNaN() method of the Date object to determine whether it is a date.
First use the isNaN() method to exclude pure numbers, and then use the Date.parse() method to determine whether it is a date.
Implementation code:
var data = "2021-11-03" if(isNaN(data) && !isNaN(Date.parse(data))) { console.log(data+" 是日期格式!"); }
Description:
isNaN() function is used to check its Whether the parameter is a non-numeric value. If the parameter value is NaN or a non-numeric value such as string, object, undefined, etc., it returns true, otherwise it returns false.
The parse() method parses a date and time string and returns the number of milliseconds from midnight on January 1, 1970 to the date and time.
Syntax: Date.parse(datestring)
datestring: required parameter, a string representing date and time.
Return value: The number of milliseconds between the specified date and time 1970/1/1 midnight (GMT time).
Description: This method is a static method of Date object. This method is generally called in the form of Date.parse() rather than through dateobject.parse().
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to determine if it is a date in JavaScript. For more information, please follow other related articles on the PHP Chinese website!