【问题标题】:NSDateFormatter dateFromString coming back nullNSDateFormatter dateFromString 返回 null
【发布时间】:2012-02-06 21:57:13
【问题描述】:

我正在尝试将字符串日期转换为日期对象,以便进行一些比较。我的代码如下:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy/MM/dd_hh:mm:ss"];
NSDate *date = [formatter dateFromString:@"2012/02/06_20:35:59"]; 
[formatter release];

NSLog(@"date = %@", date);

我的 NSLog 显示 *date = null;

感谢任何帮助。谢谢。

【问题讨论】:

    标签: objective-c nsstring nsdateformatter


    【解决方案1】:

    你的格式不需要是yyyy/MM/dd_HH:mm:ss吗?

    hh 是 0-12,而 HH 是 0-23。

    作为参考,这是我从中获得信息的文档 - http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns

    【讨论】:

    • 哇..谢谢老兄。做到了.. 坐在这里盯着它看了一个小时。
    【解决方案2】:
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *date = [formatter dateFromString:@"2012-02-06 20:35:59"]; 
        [formatter release];
    
        NSLog(@"date = %@", date);
    
    
    d Day of the month as digits; no leading zero for single-digit days.
    dd Day of the month as digits; leading zero for single-digit days.
    ddd Day of the week as a three-letter abbreviation.
    dddd Day of the week as its full name.
    m Month as digits; no leading zero for single-digit months.
    mm Month as digits; leading zero for single-digit months.
    mmm Month as a three-letter abbreviation.
    mmmm Month as its full name.
    yy Year as last two digits; leading zero for years less than 10.
    yyyy Year represented by four digits.
    h Hours; no leading zero for single-digit hours (12-hour clock).
    hh Hours; leading zero for single-digit hours (12-hour clock).
    H Hours; no leading zero for single-digit hours (24-hour clock).
    HH Hours; leading zero for single-digit hours (24-hour clock).
    M Minutes; no leading zero for single-digit minutes.
    Uppercase M unlike CF timeFormat‘s m to avoid conflict with months.
    MM Minutes; leading zero for single-digit minutes.
    Uppercase MM unlike CF timeFormat‘s mm to avoid conflict with months.
    s Seconds; no leading zero for single-digit seconds.
    ss Seconds; leading zero for single-digit seconds.
    

    【讨论】:

      猜你喜欢
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      相关资源
      最近更新 更多