2

I need to extract the date from json :

/Date(1224043200000)/ 

I saw That I can do it by :

var date = new Date(parseInt('/Date(1224043200000)/'.substr(6))); 
                                    ^
                                    |
------------------------------0123456

But how does substr knows to ignore the last chars ? [)/]

I've searched at mdn , but couldn't find the documented behaviour.

Community
  • 1
  • 1
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 1
    It's not `substr` that skips the last non numeric chars, it's `parseInt`. To be on the save side, I'd rather go with the `length` parameter to `substr`. – Yoshi Sep 19 '12 at 07:46
  • 2
    Sidenote: to prevent strange behavior always use `parseInt()` with the radix parameter! – Sirko Sep 19 '12 at 07:49
  • 1
    I know ....`parseInt('010')=>8` (octal base) – Royi Namir Sep 19 '12 at 07:50

3 Answers3

4

.substr() return everything after the 6th char.

But parseInt() will parse all numeric chars until it reaches a non numeric char, so the ignoring happens by parseInt


Quoting the docs

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
2

Try this:

var date = new Date(parseInt('/Date(1224043200000)/'. substring(6, indexOf(")")-1 )); 
gimpf
  • 4,503
  • 1
  • 27
  • 40
CRDave
  • 9,279
  • 5
  • 41
  • 59
2

I'd go about this another way. Gaby explained about parseInt, but a note of caution: parseInt interprets integers with leading zeroes as octals. This might not apply in your case, but IMO, this is a safer approach:

var date = new Date(+('/Date(1224043200000)/'.match(/\d+/)[0]));

First, '/Date(1224043200000)/'.match(/\d+/) extracts the numbers from the string, in an array: ["1224043200000"].
We then need the first element of these matches, hence the [0].
To be on the safe side, I wrapped all this in brackets, preceded by a + sign, to coerce the matched substring to a number: +('/Date(1224043200000)/'.match(/\d+/)[0]) === 1224043200000
This is passed to the Date constructor, which creates a date object with "Wed Oct 15 2008 06:00:00 GMT+0200 (Romance Daylight Time)" as a string value

To catch any possible errors, you might want to split this one-liner up a bit, but that's up to you :)

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149