5

I need to parse a Python-generated datetime string into a Javascript Date object. I went the simplest route:

In Python:

dstring = str(mydate)

example dstring = '2012-05-16 19:20:35.243710-04:00'

In Javascript (with datejs library):

d = new Date(dstring);

This gets me a correct date object in Chrome, but an "Invalid Date" error in Firefox and Safari (on Mac).

Yarin
  • 173,523
  • 149
  • 402
  • 512
  • possible duplicate of [javascript dates in IE, NAN - firefox & chrome ok](http://stackoverflow.com/questions/2182246/javascript-dates-in-ie-nan-firefox-chrome-ok) – Falmarri May 16 '12 at 23:50

1 Answers1

1

You need to parse the string into a JS Date. The Date constructor is not enough. Maybe you should consider using a library such as datejs:

http://www.datejs.com/

Datejs extends the Date object with useful methods such as:

Date.parse('Thu, 1 July 2004 22:30:00');

Needless to say that date/time formats are customizable.

ubik
  • 4,440
  • 2
  • 23
  • 29
  • as a matter of fact I *am* using datejs already- didn't even realize, I've updated my question. So the library itself isn't working in ffox/safari?.. – Yarin May 16 '12 at 23:50
  • But if you are invoking it as you say in your post, you are doing it wrong. You should do it as I show in my answer: `d = Date.parse('...');` – ubik May 16 '12 at 23:53
  • Sorry Pedro I missed that- doing it now, but getting a null result – Yarin May 16 '12 at 23:58
  • @Yarin, cause your date is in a format that datejs does not recognize. Try keeping only the first 19 chars of your date string (`date_string.slice(0,19)`) and it should work. – ubik May 17 '12 at 00:04
  • But that loses timezone- there's got to be a way to parse ISO dates – Yarin May 17 '12 at 00:05
  • Actually, I can ignore timezones for this use case, so this takes care of it for me. Thanks Pedro you the man- – Yarin May 17 '12 at 00:10
  • Yeah, I don't think `parseExact`'s syntax supports timezones anyway :/ – ubik May 17 '12 at 00:26