1

Novice question. I've got a string in the following format:

var dateStr = '2012-4-14';

I want to make it into a JavaScript Date object. The following creates a Date object in Chrome, but is NaN in IE8:

var myDate = new Date(dateStr);

What should I be doing differently - should I split the string?

Thanks!

flossfan
  • 10,554
  • 16
  • 42
  • 53

3 Answers3

3

Try splitting your date string into year, month, day and instantiating your date differently.

var rawDate = '2012-4-14'.split('-');

var myDate = new Date(rawDate[0], rawDate[1]-1, rawDate[2]);

Note that this will only work if you can guarantee that your date string will be of the same format each time.

Michael Robinson
  • 29,278
  • 12
  • 104
  • 130
  • 1
    Don't forget that months are 0 based in JavaScript, so you should subtract `1` from the month if April is desired.. –  Jul 25 '12 at 20:48
  • 1
    @amnotiam I can't believe I missed that! Considering that this bit me in the *** just the other day. – Michael Robinson Jul 25 '12 at 20:49
2

There's a Date.parse in javascript, it recognizes various date formats, see the MDN page for details. For ISO 8601 dates (yours seem to be this one) you can use this library.

This answer also could prove itself useful: Why does Date.parse give incorrect results?

Community
  • 1
  • 1
complex857
  • 20,425
  • 6
  • 51
  • 54
0

Change var dateStr = '2012-4-14'; to var dateStr = '2012/4/14';

j08691
  • 204,283
  • 31
  • 260
  • 272