【问题标题】:NSDateFormatter doesn't convert my NSString in NSDateNSDateFormatter 不会在 NSDate 中转换我的 NSString
【发布时间】:2012-01-14 21:15:01
【问题描述】:

我有一个字符串,需要将其转换为日期,但它不能正确转换。我不知道为什么...我的代码是:

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)

【问题讨论】:

    标签: objective-c nsstring nsdate nsdateformatter


    【解决方案1】:

    我认为您需要yyyy-MM-dd HH:mm:ss.SSS,而不是格式字符串yyyy-MM-dd HH:mm:ss.ZZZ

    ZZZ 将是一个时区值,而 SSS 是小数秒。

    查看Unicode documentation(链接自Apple 的文档Data Formatting

    编辑:另一件事:你不需要有NSDate *dateFromString = [[NSDate alloc] init]; 这一行。只需致电NSDate *dateFromString = [dateFormatter dateFromString:fecha];。日期格式化程序将根据需要分配日期对象。

    【讨论】:

    • 如果你不需要那条线,它会导致内存泄漏。
    【解决方案2】:

    ZZZ 是一种时区格式,它正在寻找类似CET 的东西,而不是秒的小数部分。你要SSS

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多