Get NSDate from JSON Date format Date1268123281843
suggest changePrior to Json.NET 4.5, dates were written in the Microsoft format “/Date(1198908717056)/”. If your server sends dates in this format, you can parse them into an NSDate. rangeOfString: returns NSNotFound when ( or ) is missing, and this method does not check for that. Divide by 1000.0 so the milliseconds are not truncated to whole seconds.
Objective-C
- (NSDate *)getDateFromJSON:(NSString *)dateString
{
// Expect date in this format "/Date(1268123281843)/"
NSUInteger startPos = [dateString rangeOfString:@"("].location + 1;
NSUInteger endPos = [dateString rangeOfString:@")"].location;
NSRange range = NSMakeRange(startPos, endPos - startPos);
unsigned long long milliseconds = [[dateString substringWithRange:range] longLongValue];
NSLog(@"%llu", milliseconds);
NSTimeInterval interval = milliseconds / 1000.0;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
// add code for date formatter if need NSDate in specific format.
return date;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents