12

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?

Rahul Desai
  • 15,242
  • 19
  • 83
  • 138

5 Answers5

66

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());
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
4

Try: var dateString = "02/24/2014 09:22:21 AM"

dd-mm-yyyy is not a standard date format in EcmaScript. Some browsers implement it, some don't.

You tried replaceing hyphens with baskslashes, but you need to replace them with slashes.

if a date with hyphens comes from your server or something you can replace them using replace method and regex:

var dateString = "02-24-2014 09:22:21 AM";
dateString = dateString.replace(/-/g, '/');
kamilkp
  • 9,690
  • 6
  • 37
  • 56
4

Please try this:

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

var dateObject = new Date();

dateObject.toDateString(dateString);

1

i will suggest you to use,

http://momentjs.com/

moment.js jQuery api.It works on all browers. There are many ways to do same task. but easiest way is to add moment.js.

 var dateString=moment('date as string').toDate();

http://jsfiddle.net/cTcNK/5/

govinda
  • 51
  • 9
0

I advise you to use the ISO8601 (http://en.wikipedia.org/wiki/ISO_8601) format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.

So: new Date('2014-02-24T09:22:21')

If the string is fixed... then split it and use Date constructor like

new Date('2014', '02' - 1, '24', '09', '22', '21')
Alberto
  • 1,853
  • 1
  • 18
  • 22