Nitish Nitish - 1 month ago 6
iOS Question

Date format for 2016-10-20T13:01:47.317

This is what I am trying for getting date from the string 2016-10-20T13:01:47.317 but getting

nil


NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
dateString = [dateString substringToIndex:dateString.length - 3];
[dateFormatter1 setDateFormat:@"YYYY-MM-ddTHH:mm:ss"];
NSDate *date = [dateFormatter1 dateFromString:dateString];


Also tried with yyyy but still getting nil.

I was not able to understand .317 so I eliminated that from the string. What shall be the date format for this ?

Answer

it .317 means milliseconds use SSS

NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:@"yyyy-MM-ddTHH:mm:ss.SSS"]; // or omit the timezone use `yyyy-MM-dd'T'HH:mm:ss.SSS`
 NSDate *date = [dateFormatter1 dateFromString:dateString];