-->

NSDateFormatter doesn't convert my NSString in

2020-04-11 09:47发布

问题:

I have a string and need convert it to a date, but it doesn't convert correctly. I don't know why... my code is:

NSString * fecha = @"2011-12-07 11:11:29.657";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.ZZZ"];

NSDate *dateFromString = [[NSDate alloc] init]; 
dateFromString = [dateFormatter dateFromString:fecha]; 

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [calendar components:units              
                                           fromDate:dateFromString];
 NSInteger* hour = [components hour];
 NSInteger* minute = [components minute];
 NSInteger* second = [components second];  

NSLog(@"Fecha: %@",fecha);
NSLog(@"Format: %@",dateFormatter.dateFormat);
NSLog(@"date: %@",dateFromString);

In my log:

2011-12-07 11:36:11.750 Catalogo-V1[13741:207] Fecha: 2011-12-07 11:11:29.657
2011-12-07 11:36:11.750 Catalogo-V1[13741:207] Format: yyyy-MM-dd HH:mm:ss.ZZZ
2011-12-07 11:36:11.751 Catalogo-V1[13741:207] date: (null)

回答1:

I think that instead of the format string yyyy-MM-dd HH:mm:ss.ZZZ, you will want yyyy-MM-dd HH:mm:ss.SSS.

ZZZ will be a timezone value, whereas SSS is fractional seconds.

See the Unicode documentation (linked from Apple's docs on Data Formatting)

Edit: one other thing: you don't need to have the line NSDate *dateFromString = [[NSDate alloc] init];. Just call NSDate *dateFromString = [dateFormatter dateFromString:fecha];. The date formatter will allocate the date object as it needs to.



回答2:

ZZZ is a time zone format, it's looking for something like CET not the fractional part of the seconds. You want SSS

@"yyyy-MM-dd HH:mm:ss.SSS"

http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns