admin管理员组

文章数量:1323732

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?

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?

Share Improve this question asked Sep 12, 2009 at 22:19 KjensenKjensen 12.4k39 gold badges114 silver badges179 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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())

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 pensate 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());

maybe this question can help you.

if you use jquery this can be useful too

本文标签: javascriptParsing a date in long format from ATOM feedStack Overflow