我有一個字符串,需要將其轉換爲日期,但它不能正確轉換。我不知道爲什麼......我的代碼是:NSDateFormatter不轉換我的NSString NSDate
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);
在我的日誌:
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)
比您不需要擁有該行更重要的是,它會導致內存泄漏。 –