【问题标题】:Parsing NSString to NSDate using NSDateFormatter使用 NSDateFormatter 将 NSString 解析为 NSDate
【发布时间】:2013-10-22 12:11:12
【问题描述】:

我有这样的字符串:“2013 年 10 月 22 日星期二 1:59 pm EEST” 我正在尝试设置这些解析规则:

[formatter setDateFormat: @"EEE, dd MMM yyyy hh:mm a z"];

但是当我执行时这会返回nil

[formatter dateFromString: @"Tue, 22 Oct 2013 1:59 pm EEST"];

这种格式的正确正则表达式是什么?

【问题讨论】:

  • 只是提示,不会解决您的问题,您应该将 dateformatter 的本地设置为英文。因为如果您的 iOS 设备设置为英语,您的日期格式将失败。
  • 是的,可能是语言环境问题。由于您使用的是英语术语,因此您应该使用英语/美国语言环境。

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:
 NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"EEE, dd MMM yyyy hh:mm a zzz"];
    [formatter setLocale:locale];
    NSDate* date = [formatter dateFromString:@"Tue, 22 Oct 2013 1:59 PM EEST"];
    NSLog(@"date: %@",date);

O/P:-date: 2013-10-22 10:59:00 +0000

【讨论】:

    【解决方案2】:

    hh 是一个填充小时(在您的情况下为“01”),但您的字符串没有填充小时(只有“1”),所以它应该只是 h

    您可以在下面看到不同格式组件的实际示例(来自this GitHub gist 的输出)。被格式化的日期是1987-08-27 15:24:03

    format  result
    --------------
        yy  87
      yyyy  1987
         M  8
        MM  08
       MMM  Aug
      MMMM  August
        dd  27
        HH  15
        hh  03    // <--.
         h  3     // <--'--- note the difference
         a  PM
        mm  24
         m  24
        ss  03
         s  3
    

    【讨论】:

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