objective-cjsondatedatetimejsonmodel

How to deserialize JSON date to NSDate in objective-c?


I have a Source date string

/Date(1455895287677-0500)/

in objective-c. I need to convert it to format like "2015-01-01 HH:MM:SS"

How can I convert it to Date or NSDate?

I'm using JSONModel, but it seems not working.


Solution

  • Well, it's a non-standard format for dates. Looks like milliseconds since 1970, plus time zone. You DON'T need to convert it to something like "2015-01-01 HH:MM:SS", you want an NSDate.

    Take the string, check that it starts with /Date( and ends with )/ and remove these, check whether there is a + or - in between, split into the part before the + or - and the part starting with the + or -, call doubleValue for the first part and divide by 1000 (so you have seconds since 1970), call integerValue for the second part, so you get hours and minutes but in a decimal format. Take that integer value, divide by 100 to get hours, subtract hours times 100 from the number, what remains is minutes. Add hours * 3600 and minutes * 60 to the time. Then [NSDate dateWithTimeIntervalSince1970].

    Obviously do some testing, log if there is anything that you didn't expect and make sure you handle it.