Reputation: 148524
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.
Upvotes: 2
Views: 297
Reputation: 195992
.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
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.
Upvotes: 4
Reputation: 76405
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 :)
Upvotes: 2
Reputation: 9285
Try this:
var date = new Date(parseInt('/Date(1224043200000)/'. substring(6, indexOf(")")-1 ));
Upvotes: 2