2

I get this date in javascript from an rss-feed (atom):

2009-09-02T07:35:00+00:00

If I try Date.parse on it, I get NaN.

How can I parse this into a date, so that I can do date-stuff to it?

Kjensen
  • 12,447
  • 36
  • 109
  • 171

3 Answers3

4

Here is my code, with test cases:

function myDateParser(datestr) {
var yy   = datestr.substring(0,4);
var mo   = datestr.substring(5,7);
var dd   = datestr.substring(8,10);
var hh   = datestr.substring(11,13);
var mi   = datestr.substring(14,16);
var ss   = datestr.substring(17,19);
var tzs  = datestr.substring(19,20);
var tzhh = datestr.substring(20,22);
var tzmi = datestr.substring(23,25);
var myutc = Date.UTC(yy-0,mo-1,dd-0,hh-0,mi-0,ss-0);
var tzos = (tzs+(tzhh * 60 + tzmi * 1)) * 60000;
return new Date(myutc-tzos);
}


javascript:alert(myDateParser("2009-09-02T07:35:00+00:00"))
javascript:alert(myDateParser("2009-09-02T07:35:00-04:00"))
javascript:alert(myDateParser("2009-12-25T18:08:20-05:00"))
javascript:alert(myDateParser("2010-03-17T22:30:00+10:30").toGMTString())
Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Robert L
  • 1,963
  • 2
  • 13
  • 11
3

You can convert that date into a format that javascript likes easily enough. Just remove the 'T' and everything after the '+':

var val = '2009-09-02T07:35:00+00:00',
    date = new Date(val.replace('T', ' ').split('+')[0]);

Update: If you need to compensate for the timezone offset then you can do this:

var val = '2009-09-02T07:35:00-06:00',
    matchOffset = /([+-])(\d\d):(\d\d)$/,
    offset = matchOffset.exec(val),
    date = new Date(val.replace('T', ' ').replace(matchOffset, ''));
offset = (offset[1] == '+' ? -1 : 1) * (offset[2] * 60 + Number(offset[3]));
date.setMinutes(date.getMinutes() + offset - date.getTimezoneOffset());
Prestaul
  • 83,552
  • 10
  • 84
  • 84
  • 1
    How can you remove everything after "+" if it denotes timezone offset? Shouldn't resulting date be adjusted appropriately? – kangax Sep 13 '09 at 04:35
  • It depends on how he intends to use it, but that is a good point. – Prestaul Sep 13 '09 at 06:57
  • Living in +00:00 timezone has its advantages. ;) – Kjensen Sep 13 '09 at 11:34
  • I don't think this would work because "val" minus the "T" and everything after the "+" is still not a valid date string, you'd need to replace the "-"s with "/"s too. Also the second replace cant work because "matchOffset" is an array, "replace(matchOffset[0], '')" would work though. – Jonathon Oates Nov 29 '10 at 15:46
  • @Jonathon, I assure you that it does work. The Date constructor can handle a wide variety of input formats, and matchOffset is not an array, it is a regular expression. – Prestaul Dec 07 '10 at 21:15
-1

maybe this question can help you.

if you use jquery this can be useful too

Community
  • 1
  • 1
Gabriel Sosa
  • 7,897
  • 4
  • 38
  • 48