Search code examples
objective-cnsdatensdateformatter

Date formatting using NSDateFormatter


I'm trying to get date asNSString. I'm receiving date in the format 2017-05-05T04:42:44.954604Z

Below is the code in which I'm trying to apply NSDateFormatter

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *newdate = [utcDate stringByReplacingOccurrencesOfString:@"T" withString:@" "];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.Z"];
msgDate = [dateFormatter dateFromString:newdate];

But msgDate is showing nil


Solution

  • use 'SS' specifier (with number of S's equal to number of digits you want to get - 6 in your case)

    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"];
    

    instead of

     NSString *newdate = [utcDate stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.Z"];
    

    UPDATE

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"];
     NSDate *msgDate = [dateFormatter dateFromString:@"2017-05-05T04:42:44.954604Z"];
    

    OUTPUT

    enter image description here