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!
Your date format is incorrect. It should be:
The three capital 'S' means it will take the fractional part to 3 digits. Adjust it as you will.
Use this date format:
Your code with little modification:
gives me this output:
Edit: how "ikinci viking" pointed out in comment, escaping the dashes is unnecessary. Escaping removed from the code
Update for iOS 11+
ISO8601DateFormatter
is the recommended way to parse internet date on iOS 10+.However it has few issues preventing it from usage with the specific format from the question:
+00:00
orZ
for "Zulu time" UTC)If date strings contains both milliseconds and timezone (e.g.
2018-09-07T14:04:13.143Z
), it can be used as follows (Swift example):