JSON date with offset to NSDate
I am developing an Cocoa application on th开发者_如何学Ce Mac and I am consuming a WCF service which is returning me a JSON date which comes from a SQL Server DATETIMEOFFSET field. The JSON object returned from the service including the date fields is outlined below:
{
"ObjectId": 1,
"Name": "My Object Name",
"Description": "My Object Description",
"CreateDate": {
"DateTime": "/Date(1306481778297)/",
"OffsetMinutes": 0
},
"LastModifiedDate": {
"DateTime": "/Date(1306936930427)/",
"OffsetMinutes": 0
}
}
My question is how do I convert the CreateDate and LastModifiedDate fields to NSDate objects?
I attempted to create a NSDateFormatter and abstract the value that way. However this works for simple string dates or the standard JSON date (/Date(1306936930427)/) but not the the date object containing the date and the offset.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]
NSString *creationDate = [myObject valueForKey:@"CreateDate"];
NSDate *date = [dateFormatter dateFromString:creationDate];
Any help on this one will be much appreciated.
First, extract the number from the string (e.g. 1306936930427); NSScanner might come in handy for this. Then divide it by 1000.0 and use NSDate's dateWithTimeIntervalSince1970:
class method to get your NSDate.
精彩评论