Antonio Laguna
Antonio Laguna

Reputation: 9292

JavaScript date object issue on Explorer

I'm having a weird issue with Internet Explorer which is not converting a valid string date to JavaScript Date method.

The string is as the following:

2011-12-26T13:55:49.377Z

It's working fine on Chrome and Firefox but not on Explorer.

This is the code:

var now = new Date;
var call_start = new Date(call.start);
var difference = now .getTime() - call_start.getTime();

call.start is valid but call_start is NaN so the Difference is NaN.

What's the problem here?

I really need the miliseconds here...

Upvotes: 3

Views: 135

Answers (2)

Andrew D.
Andrew D.

Reputation: 8230

function dateFromGMTString(str) {
  var x=str.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{1,3})Z/);
  return new Date(x[1],(+x[2])-1,x[3],x[4],x[5],x[6],x[7]);
}

UPDATE:

You can try to use Date.parse() method instead of Date contructor for converting GMT (JSON) like dates into javascript Date object. In this case you can try to "patch" Date.parse() for IE using next code example. Simply add this code anywhere in begining of your page javascript code:

if(Date.parse("2000-01-01T00:00:00.000Z")+new Date().getTimezoneOffset()*60000!==(+new Date(2000,0,1,0,0,0,0))) {
  (function() { // closure
    var rg=/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{1,3})Z/,
        parseOriginal=Date.parse;
    Date.parse=function(str) {
      var x=str.match(rg);
      return x?(+new Date(x[1],(+x[2])-1,x[3],x[4],x[5],x[6],x[7]))-new Date().getTimezoneOffset()*60000:parseOriginal.call(Date,str);
    }
  })();
}

After above code is executed you can use Date.parse() in all browsers (including IE) to convert string dates into javascript date objects using next code:

new Date(Date.parse("2011-12-26T13:55:49.377Z"));

Upvotes: 1

malko
malko

Reputation: 2382

we encounter same problem lately,

the easyer way is to explode your string or use regexp and set manually each part of the date object manually using methods

function getDateFromString(dString){
  var d = new Date(), m=dString.match(/(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d).(\d\d\d)Z/);
  d.setFullYear(m[1]);             // Sets the day of the month
  d.setMonth(parseInt(m[2],10)-1); // Sets the month (from 0-11)
  d.setDate(m[3]);                 // Sets the day of the month (from 1-31)
  d.setHours(m[4]);                // Sets the hour (from 0-23)
  d.setMinutes(m[5]);              // Set the minutes (from 0-59)
  d.setSeconds(m[6]);              // Sets the seconds (from 0-59)
  d.setMilliseconds(m[7]);         // Sets the milliseconds (from 0-999)
  return d;
}

thanks crapy Jscript implementation from microsoft

Upvotes: 1

Related Questions