NSDateFormatter dateFromString在一个特定日期返回nil

时间:2016-03-20 17:01:28

标签: ios objective-c iphone nsdateformatter

我的日期格式化程序在某个特定日期返回nil:" 1998年3月20日"。

+ (NSDate*)dateFromString:(NSString*)date
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setLocale:[NSLocale currentLocale]];
    if ([WPRConverter isUropeanMetrics])
        [df setDateFormat:@"dd MMM, yyyy"];
    else
        [df setDateFormat:@"MMM dd, yyyy"];
    return [df dateFromString:date];
}

我已经检查了近日期并且正确地返回了所有内容:

  • " 1997年3月20日"
  • " 1999年3月20日及#34;
  • " 1998年3月21日"
  • " 1998年3月19日"

enter image description here

我的区域设置是" en_US"。

使用[NSDateFormatter getObjectValue:forString:range:error:]让我错误:

  

“1998年3月20日”的值无效。失败原因:价值“20 Mar,   1998年“无效。 RecoverySuggestion:请提供有效值。   RecoveryOptions:代码:2048

1 个答案:

答案 0 :(得分:2)

这与以色列的timeZone有关,它有一天的节约时间变化(见http://timeanddate.com/time/change/israel/karmiel?year=1998)。

将时区更改为GMT:

formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]

应该解决问题。

相关问题