4

I want to parse date in my page to Javascript's Date.

So I have this in my page

<span>01-07-2012 01:04 PM</span>

And I have Javascript code that parses this value to date

var tagText = $(this).html();
var givenDate = new Date(tagText);
alert(givenDate);

And here is what I get in different browsers

IE:

Sat Jan 7 13:04:00 UTC+0400 2012

Chrome:

Sat Jan 07 2012 13:04:00 GMT +0400 (Caucasus Standard Time)

Firefox:

Invalid Date

Why Firefox doesn't recognize my date? What I must change to make it work with all major browsers?

Here is jsfiddle http://jsfiddle.net/mgER5/1/

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123

4 Answers4

9

try this:

var tagText = $(this).html();
tagText = tagText.replace(/-/g, '/');
var givenDate = new Date(tagText);
alert(givenDate);
redmoon7777
  • 4,498
  • 1
  • 24
  • 26
2

As explained in the documentation the string you are passing to the constructor of the Date object should be:

String value representing a date. The string should be in a format recognized by the parse method (IETF-compliant RFC 1123 timestamps).

Basically it should represent an RFC822 or ISO 8601 date.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

If you really want full cross-browser support for any date format, you should take a look at moment.js. It allows you to be explicit about the input format. For example:

var m = moment('01-07-2012 01:04 PM', 'DD-MM-YYYY  hh:mm a');
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
0

What I must change to make it work with all major browsers?

Write it in milliseconds.

YuS
  • 2,025
  • 1
  • 15
  • 24