Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript date.parse difference in chrome and other browsers

Tags:

javascript

I have a date string "2011-11-24T09:00:27+0000" fetched from the graph.facebook API.

When I run

var timestamp = Date.parse(facebookDate);

in chrome. I get a timestamp that relates to the date! perfect!

But in EVERY other major browser... I get "NaN" !!! ?

Surely all these browsers use the same javascript parse function right?

Can anybody explain why the same javascript function give different results?

And can anybody also tell me how to fix this issue...

Thanks in advance

Alex

like image 860
AlexMorley-Finch Avatar asked Nov 25 '11 09:11

AlexMorley-Finch


1 Answers

Here is a fix for Firefox and IE/Safari (with the help from JavaScript: Which browsers support parsing of ISO-8601 Date String with Date.parse ) :

DEMO

var noOffset = function(s) {
  var day= s.slice(0,-5).split(/\D/).map(function(itm){
    return parseInt(itm, 10) || 0;
  });
  day[1]-= 1;
  day= new Date(Date.UTC.apply(Date, day));  
  var offsetString = s.slice(-5)
  var offset = parseInt(offsetString,10)/100;
  if (offsetString.slice(0,1)=="+") offset*=-1;
  day.setHours(day.getHours()+offset);
  return day.getTime();
}

From MDN

JavaScript 1.8.5 note

A subset of ISO 8601 formatted date strings can now also be parsed.

Alternatively, the date/time string may be in ISO 8601 format. Starting with JavaScript 1.8.5 / Firefox 4, a subset of ISO 8601 is supported. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00 (date and time) can be passed and parsed. Timezones in ISO dates are not yet supported, so e.g. "2011-10-10T14:48:00+0200" (with timezone) does not give the intended result yet.

like image 161
mplungjan Avatar answered Oct 21 '22 21:10

mplungjan