0

I have this time stamp format for each car in my map:

2012-12-11T03:51:43+03:00

I want to extract the number of hours from it according to current time.

I don't know how to parse this string then compare it to current time.

Any Idea ?

Salman A
  • 262,204
  • 82
  • 430
  • 521
Shadin
  • 1,867
  • 5
  • 26
  • 37
  • Just to add to Yoshi's answer, you might look at using a library like [MomentJS](http://momentjs.com) for the parsing part, since even IE8 won't parse that string. – T.J. Crowder Dec 11 '12 at 09:21

2 Answers2

2

something like:

var
  d1 = new Date('2012-12-11T03:51:43+03:00'),
  d2 = new Date;

console.log(
  (d2 - d1) / 3600000
);
Yoshi
  • 54,081
  • 14
  • 89
  • 103
  • @ Yoshi: No, actually, since you're doing the date math, it'll using milliseconds-since-the-epoch and the timezones should fall out. – T.J. Crowder Dec 11 '12 at 09:05
  • But do beware that not all browsers support parsing that date string. That format was only introduced in ES5 (so, about three years ago) and doesn't work on older browsers. – T.J. Crowder Dec 11 '12 at 09:06
  • @T.J.Crowder ok, that may be for I did only check chrome. – Yoshi Dec 11 '12 at 09:06
  • Could be fixed with some regex find/replace. – Salman A Dec 11 '12 at 09:10
  • @SalmanA: No, you'd be better off properly parsing it. If you do the regex thing, you'll A) be off into unspecified territory, and B) *probably* be working in the local timezone (again, though unspecified). – T.J. Crowder Dec 11 '12 at 09:10
  • I'm with T.J.Crowder here, if the target platform does not allow parsing the string like this, I would not even try to fix that, and instead go for a completely different solution. – Yoshi Dec 11 '12 at 09:12
  • @mplungjan: You shouldn't need to do anything to it for Firefox (I don't). IE8, though, will fail, as will earlier versions. – T.J. Crowder Dec 11 '12 at 09:13
  • I am talking about transforming the string `'2012-12-11T03:51:43+03:00'` into `2012-12-11 03:51:43 GMT+03:00`. Should work? – Salman A Dec 11 '12 at 09:13
0

You need to first fix the timestamp for other browsers than Chrome

javascript date.parse difference in chrome and other browsers

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();
}
alert(parseInt((new Date().getTime()-noOffset(yourTimeStamp))/3600000))
Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236