Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while converting date string to Date object in Firefox [duplicate]

Tags:

javascript

I am converting a simple dateString to Date object. The following code works perfectly on all browsers except Firefox.

var dateString = "02-24-2014 09:22:21 AM";

var dateObject = new Date(dateString);

console.log(dateObject.toDateString());

The Firebug console in Firefox says Invalid Date. What am I doing wrong here?

I also tried replacing - with \, but it didnt help.

Is it possible to do this without using any libraries?

like image 388
Rahul Desai Avatar asked Feb 24 '14 10:02

Rahul Desai


1 Answers

Looks like Firefox does not like the - in dateString.

Replace all occurrences of - with / using a regular expression and then convert the string to Date object.

var str = '02-24-2014 09:22:21 AM';

str = str.replace(/-/g,'/');  // replaces all occurances of "-" with "/"

var dateObject = new Date(str);

alert(dateObject.toDateString());
like image 86
Rahul Desai Avatar answered Oct 02 '22 16:10

Rahul Desai