How to parse string to a Javascript date

Description

The Date.parse() method accepts a string argument representing a date.

The following date formats are supported:

FormatExample
month/date/year7/24/2012
month_name date, yearJanuary 31, 2021
day_of_week month_name date year hours:minutes:seconds time_zoneTue May 27 2012 12:34:56 GMT-0400
ISO 8601 extended format YYYY-MM-DDTHH:mm:ss.sssZ2012-0525T00:00:00

Example

The following code passes a string date value into the parse() function.


var aDate= new Date(Date.parse("May 21, 2012")); 
console.log(aDate);/*ww w .j av  a  2  s .  co  m*/
//Mon May 21 2012 00:00:00 GMT-0700 (Pacific Daylight Time)

aDate= new Date(Date.parse("asdf 21, 2012")); 
console.log(aDate);//Invalid Date

If the string passed into Date.parse() doesn't represent a date, then it returns NaN. Chrome returns a string:'Invalid Date'.

The code above generates the following result.

Example 2

The Date constructor calls Date.parse() if a string is passed in


var aDate = new Date("May 25, 2004"); 
console.log(aDate);
//Tue May 25 2004 00:00:00 GMT-0700 (Pacific Daylight Time)

The code above generates the following result.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window