Regarding JavaScript new Date() and Date.parse()

var exampleDate='23-12-2010 23:12:00';  

I want to convert above string into a date and have tried a couple things:

var date = new Date(exampleDate); //returns invalid Date
var date1 = Date.parse(exampleDate); //returns NAN

This code is running fine in IE and Opera, but date is returning me an invalid Date and date1 is returning NAN in Firefox. What should I do?


Solution 1:

The string in your example is not in any of the standard formats recognized by browsers. The ECMAScript specification requires browsers to be able to parse only one standard format:

The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

This format includes date-only forms:

YYYY

YYYY-MM

YYYY-MM-DD

It also includes time-only forms with an optional time zone offset appended:

THH:mm

THH:mm:ss

THH:mm:ss.sss

Also included are “date-times” which may be any combination of the above.

If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. Unrecognizable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN.

So in your example, using 2010-12-23T23:12:00 is the only string guaranteed to work. In practice, most browsers also allow dates of the format DD Month YYYY or Month DD, YYYY, so strings like 23 Dec 2010 and Dec 23, 2010 could also work.

Solution 2:

Above format is only supported in IE and Chrome.

so try with another formats. following are some formats and there supporting browsers.

<script type="text/javascript">

//var dateString = "03/20/2008";  // mm/dd/yyyy [IE, FF]

 var dateString = "2008/03/20";  // yyyy/mm/dd [IE, FF]
// var dateString = "03-20-2008";  // mm-dd-yyyy [IE, Chrome]
// var dateString = "March 20, 2008";  // mmmm dd, yyyy [IE, FF]
// var dateString = "Mar 20, 2008";  // mmm dd, yyyy [IE, FF]

// Initalize the Date object by passing the date string variable
var myDate = new Date(dateString);
alert(myDate); 
</script>

Solution 3:

You could parse it manually with a regular expression then call the date constructor with the date elements, as such:

var parseDate = function(s) {
  var re = /^(\d\d)-(\d\d)-(\d{4}) (\d\d):(\d\d):(\d\d)$/;
  var m = re.exec(s);
  return m ? new Date(m[3], m[2]-1, m[1], m[4], m[5], m[6]) : null;
};
var dateStr = '23-12-2010 23:12:00';
parseDate(dateStr).toString(); //=> Thu Dec 23 2010 23:12:00 GMT-0800

Solution 4:

JavaScript should support conversion at least from the following dateStrings:

* yyyy/MM/dd
* MM/dd/yyyy
* MMMM dd, yyyy
* MMM dd, yyyy

Try with:

  var exampleDate='12/23/2010 23:12:00';
  var date = new Date(exampleDate); 

Solution 5:

Use datejs and this code:

var exampleDate='23-12-2010 23:12:00';
var myDate = Date.parseExact(exampleDate, 'dd-MM-yyyy hh:mm:ss');

myDate should be a correctly constructed Date object.