In my iOS class @FHNW I set the students a task for creating a CRUD application. The backend is an existing .net REST WebService with JSON. Unfourtanatly Microsoft has decided to create their own date formate instead of using a standard like RFC1123. Therefore the solution to display the date correctly or parsing an NSDate is not strait forward.
You can parse the date the the following snipped:
+ (NSDate *)mfDateFromDotNetJSONString:(NSString *)string { static NSRegularExpression *dateRegEx = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ dateRegEx = [[NSRegularExpression alloc] initWithPattern:@"^\\/date\\((-?\\d++)(?:([+-])(\\d{2})(\\d{2}))?\\)\\/$" options:NSRegularExpressionCaseInsensitive error:nil]; }); NSTextCheckingResult *regexResult = [dateRegEx firstMatchInString:string options:0 range:NSMakeRange(0, [string length])]; if (regexResult) { // milliseconds NSTimeInterval seconds = [[string substringWithRange:[regexResult rangeAtIndex:1]] doubleValue] / 1000.0; // timezone offset if ([regexResult rangeAtIndex:2].location != NSNotFound) { NSString *sign = [string substringWithRange:[regexResult rangeAtIndex:2]]; // hours seconds += [[NSString stringWithFormat:@"%@%@", sign, [string substringWithRange:[regexResult rangeAtIndex:3]]] doubleValue] * 60.0 * 60.0; // minutes seconds += [[NSString stringWithFormat:@"%@%@", sign, [string substringWithRange:[regexResult rangeAtIndex:4]]] doubleValue] * 60.0; } return [NSDate dateWithTimeIntervalSince1970:seconds]; } return nil; }
This solution is copied from stack overflow.
To produce a .net WebService compatible date string again the solution is a little bit simpler. The important parts are caring about second/millisecond base and the time zones:
+ (NSString*)dotNetJSONStringFromDate:(NSDate*)date { NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"ZZZ"]; NSString* timezone = [formatter stringFromDate:date]; int timezoneOffset = [timezone intValue] * 36; NSTimeInterval timeInterval = [date timeIntervalSince1970]; unsigned long long time=((timeInterval - timezoneOffset) * 1000); NSString* dateTimeTosend= [NSString stringWithFormat:@"/Date(%lld%@)/", time, timezone]; return dateTimeTosend; }