简体   繁体   中英

Convert NSString to date error

I'm having a strange issue converting a string to a date:

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

For some reason, the badDateString returns nil when I try to convert it to a date. I have no idea why. Is there something wrong with the date string?

Edit: The strings are coming from a Python server. I'm using dateString = date.strftime('%Y-%m-%d %H:%M:%S.%f') on this date: 2012-06-28 16:11:17 which returns 2012-06-28 16:11:17.999771 which is unable to be parsed by the date formatter above. Any python people know how I can limit the last part of the date to 3 decimal places rather than 6?

It looks like it may be a bug. It has to do with the fact that SSS rounds the fractional seconds 999771 up to the next whole second and for some reason that causes the format to fail. If you changed the fractional seconds to 999499 it would work, but simply changing it to 9995 will cause it to fail. I would consider filing a bug report and adding it to Open Radar . In the mean-time just write code to truncate the fractional seconds past 3 digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM