使用 NSDateFormatter 格式化日期

Date formatting using NSDateFormatter

我正在尝试将日期设置为NSString。我收到格式为 2017-05-05T04:42:44.954604Z

的日期

下面是我尝试应用的代码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];

但是 msgDate 正在显示 nil

试试这个

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ";// chang
NSDate *date = [dateFormatter dateFromString:@"2017-04-13T05:57:44.886Z"];
NSString * msgDate = [dateFormatter stringFromDate:date];
 // if get nil **date** try to change this time format 

使用 'SS' 说明符(S 的数量等于您想要获得的位数 - 在您的情况下为 6)

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

而不是

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

更新

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"];

输出

 #pragma mark- Change dateFormat method
 + (NSString*) changeDateFormat:(NSString*)date
 {
     NSDateFormatter * formatter = [[NSDateFormatter alloc] init];

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

     NSDate* fromDate = [formatter dateFromString:date];
     [formatter setDateFormat:@"YYYY.MM.dd"];

     NSString* formatedDate = [formatter stringFromDate:fromDate];

     if (formatedDate == nil)
     {
         [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

         fromDate = [formatter dateFromString:date];
         [formatter setDateFormat:@"YYYY.MM.dd"];

         formatedDate = [formatter stringFromDate:fromDate];

     }
     if (formatedDate == nil)
    {
         [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];

          fromDate = [formatter dateFromString:date];
         [formatter setDateFormat:@"YYYY.MM.dd"];

         formatedDate = [formatter stringFromDate:fromDate];

    }

    return formatedDate;

 }