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.
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.
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.
As I mentioned in my question, I originally tried to use the JSONModel to deserialize date string, like "/Date(1455895287677-0500)/" but it failed. The reason is that NSDate is not supported by the JSONModel.
However, fortunately, we can achieve this goal by a few steps by modifying and adding methods to JSONModel.
Add [NSDate class] to allowedJSONTypes in JSONModel.m if you use JSONModel(https://github.com/icanzilb/JSONModel) to deserialize your JSON string.
Create a file called JSONValueTransformer+NSDate.m and .h file as well (you can rename them) in folder JSONModelTransformations.
Add this code to your newly created .m file and don't forget write interface in .h file (I planed to add the methods to JSONValueTransformer.m file, but to tell the difference, I decided to create new .m and .h files).
- (NSDate *) NSDateFromNSString:(NSString*)string {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:APIDateFormat];
return [formatter dateFromString:string];
}
Add method from provided by @jasongregori in Parsing JSON dates on IPhone to your newly created .m file.
The method in step 3 will handle the date format like "2013-08-26T15:23:37.832Z". If the date format is like this /Date(***********-****)/, you have to call method in step 4.