我正在从django REST api接收datetime.datetime字符串,但我将它们转换为NSDate对象时遇到了问题。我写了这个块来解析一个示例日期时间字符串(dateString
)
NSString *dateString =@"2014-05-31-T20:11:21.019Z";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy'-'MM'-'dd'-T'HH':'mm'.'sss'Z'"];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"date string: %@", dateString);
NSLog(@"date object: %@", date);
NSLog(@"date string: %@", [formatter stringFromDate:date]);
控制台输出如下所示:
date string: 2014-05-31-T20:11:21.019Z
date object: (null)
答案 0 :(得分:0)
您的格式错误。你没有考虑秒组件。请在下方查看。
NSString *dateString =@"2014-05-31-T20:11:21.019Z";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: @"yyyy'-'MM'-'dd'-T'HH':'mm':'ss'.'SSSZ"];
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"date string: %@", dateString);
NSLog(@"date object: %@", date);