0

Possible Duplicate:
Help parsing ISO 8601 date in Javascript

I have a set of strings, all in similar form: 2012-05-31T00:00:00.0000000

All I want to pull from this is the year (2012), the month (05), and the day (31), then construct a javascript Date object from this data.

What is the best way to parse this data?

Community
  • 1
  • 1
rwhite
  • 69
  • 1
  • 10

2 Answers2

2

The easiest way I can think of is using a regular expression, and passing the values to the Date constructor:

function parseISODate(dateString) {
    var match = /^(\d{4})-(\d\d)-(\d\d)/.exec(dateString);
    return new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
}

console.log(parseISODate('2012-05-31T00:00:00.0000000'));
// Date {Thu May 31 2012 00:00:00 GMT+0200}

Of course, you could always expand this to match the time as well...

Martijn
  • 13,225
  • 3
  • 48
  • 58
  • I keep getting an "Uncaught TypeError: cannot read property '1' of null" when I try to use this. I've verified that I'm not passing in a null string. Any idea why? – rwhite Jun 04 '12 at 21:26
  • @rwhite: that means your string doesn't match the regular expression. What is the exact contents of the string? (Also, what browser are you using?) – Martijn Jun 05 '12 at 05:21
  • I'm using Chrome and Firefox, both the most recent releases. If I do a document.write(myDateString), the page displays '2012-05-21T00:00:00.0000000'. Is there more junk that is slipping in there somehow? – rwhite Jun 05 '12 at 13:06
  • Nevermind. This works perfectly. In the area where I was trying to use your code, I was outside the scope of my date variable. Thanks very much! – rwhite Jun 05 '12 at 13:20
-1

EDIT (In UTC):

var origDate = new Date('2012-05-31T00:00:00.0000000');
var newDate = new Date(origDate.getUTCFullYear(), origDate.getUTCMonth(), origDate.getUTCDate(), 0, 0, 0, 0);
xcopy
  • 2,248
  • 18
  • 24
  • That's not cross-browser compatible; several of them won't parse a date in this format. – Martijn Jun 05 '12 at 05:23
  • Please give an example of where this code is not cross-browser compatible. I believe that this is supported in all major browsers. – xcopy Jun 05 '12 at 17:20
  • Well, IE up to 9, for example. I know some people would argue that isn’t a major browser, but still... – Martijn Jun 05 '12 at 17:22
  • Not sure where you are getting your information from but this is supported as far back as IE 7 (at least). – xcopy Jun 05 '12 at 17:26
  • Have you actually tried your code? I have. In IE9 Quirks Mode, `origDate` contains `NaN`. IE9 in Standards Mode actually throws an "Invalid Date" error. – Martijn Jun 05 '12 at 17:30
  • Actually, IE9 does support it, if you remove the `.0000000` bit. IE7 and IE8 still choke on it, though. – Martijn Jun 05 '12 at 17:41
  • This should work in all if you modify format the date string to '2012/05/31' – xcopy Jun 05 '12 at 17:45