我在将字符串转换为日期时遇到了一个奇怪的问题:
NSString *goodDateString = @"2012-06-28 16:08:56.871000";
NSString *badDateString = @"2012-06-28 16:11:17.999771";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[formatter setTimeZone:timeZone];
NSDate *goodDate = [formatter dateFromString:goodDateString];
NSDate *badDate = [formatter dateFromString:badDateString];
NSAssert(goodDate, @"date is nil"); //passes this test
NSAssert(badDate, @"date is nil"); //fails this test
出于某种原因,当我尝试将 badDateString 转换为日期时,它返回 nil。我不知道为什么。日期字符串有问题吗?
编辑:字符串来自 Python 服务器。我dateString = date.strftime('%Y-%m-%d %H:%M:%S.%f')
在这个日期使用:2012-06-28 16:11:17
它返回2012-06-28 16:11:17.999771
无法被上面的日期格式化程序解析。任何 python 人都知道我如何将日期的最后部分限制为 3 位小数而不是 6 位?