0

I am querying facebook graph api. It returns date in following format: 2012-01-23T23:52:29+0000.

I need to find difference of dates of this type in javascript. It's not a valid date in javascript ( by Date.parse() or new Date() )

I am thinking of replacing 'T' with ' ' (a space), '-' with '/' and '+0000' with '' (empty string). Is this the only way? Or am I missing something here?

Also, if this is the only way, can someone give me a regex to replace all in one go?

Execution speed is my main concern.

9

1 Answer 1

2

I'd say yes to replacing - with /, since that's that the ISO-whatever standard dictates (Facebook likes to screw things around, like <meta> tags with property attributes instead of name like they should be).

Keep the timezone part, since JS understands that and will handle it accordingly.

Overall, you want new Date(input.replace(/-/g,'/'));.

In response to comments, a better (more complete) solution would be:

new Date(input.replace(/-/g,'/').replace("T"," ").replace(/\+[0-9]+$/,''));
7
  • It throws invalid date in firefox 9.0. Works in chrome though
    – Jashwant
    Commented Jan 25, 2012 at 5:44
  • Do you have a regex for firefox too ?
    – Jashwant
    Commented Jan 25, 2012 at 5:58
  • new Date(input.replace(/-/g,'/').replace(/T|\+[0-9]+/g,'')); Commented Jan 25, 2012 at 5:59
  • en.wikipedia.org/wiki/ISO_8601 ISO 8601 have '-' in place of '/'. Its standard. This time, facebook does not screw. Firefox example is not working. 'T' should be replaced with ' ' not ''. Thanks Kolink, you made me realise that regex it not magic. I too can learn it. I thought regex can do all replacements in one go. So fool of me :(
    – Jashwant
    Commented Jan 25, 2012 at 6:15
  • Huh, insteresting. So the browsers are all wrong? Strange... Starting to wish Date.parse() were as good as PHP's strtotime()... Commented Jan 25, 2012 at 6:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.