user1491987 user1491987 - 1 month ago 19
JSON Question

JSON date to NSDate Issue

I have a date string in JSON format, it looks like this:
2013-05-22T10:54:40.437

And I'm trying to convert it to NSDate.

- (NSString *)dateFromString:(NSString *)datestring{
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss"];

NSDate *date = [dateFormat dateFromString:datestring];
//date is nil here.
NSDateFormatter *newDateFormatter = [[NSDateFormatter alloc]init];
[newDateFormatter setDateFormat:@"MM/dd/yyyy"];
NSString *newString = [newDateFormatter stringFromDate:date];
NSLog(@"Date -- %@",datestring);


return newString;
}


But date is nil after dateFromString. Does anyone know what I did wrong here?
Thanks!

Answer

Use this date format:

yyyy-MM-dd'T'HH:mm:ss.SSS

Your code with little modification:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];

NSDate *date = [dateFormat dateFromString:datestring];
NSDateFormatter *newDateFormatter = [[NSDateFormatter alloc]init];
[newDateFormatter setDateFormat:@"MM/dd/yyyy"];
NSString *newString = [newDateFormatter stringFromDate:date];
NSLog(@"Date: %@, formatted date: %@", date, newString);

gives me this output:

Date: 2013-05-22 08:54:40 +0000, formatted date: 05/22/2013

Edit: how "ikinci viking" pointed out in comment, escaping the dashes is unnecessary. Escaping removed from the code