为什么我的NSDate为空?需要帮助解析django datetimefield字符串

时间:2014-06-11 20:15:14

标签: objective-c django nsdate nsdateformatter

我正在从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)

1 个答案:

答案 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);