简体   繁体   English

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

[英]NSDateFormatter dateFromString returns nil for one specific date

My date formatter return nil for one specific date: "20 Mar, 1998". 我的日期格式化程序返回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];
}

I've checked near dates and all being returned correctly: 我检查了附近的日期,并全部正确返回:

  • "20 Mar, 1997" “ 1997年3月20日”
  • "20 Mar, 1999" “ 1999年3月20日”
  • "21 Mar, 1998" “ 1998年3月21日”
  • "19 Mar, 1998" “ 1998年3月19日”

在此处输入图片说明

My Locale is "en_US". 我的语言环境是“ en_US”。

Using [NSDateFormatter getObjectValue:forString:range:error:] gets me error: 使用[NSDateFormatter getObjectValue:forString:range:error:]使我出错:

The value “20 Mar, 1998” is invalid. 值“ 1998年3月20日”无效。 FailureReason: The value “20 Mar, 1998” is invalid. FailureReason:值“ 1998年3月20日”无效。 RecoverySuggestion: Please provide a valid value. RecoverySuggestion:请提供有效值。 RecoveryOptions: Code: 2048 RecoveryOptions:代码:2048

This is related to timeZone in Israel which had a day light saving time change (see http://timeanddate.com/time/change/israel/karmiel?year=1998 ). 这与以色列的timeZone有关, timeZone时发生了更改(请参见http://timeanddate.com/time/change/israel/karmiel?year=1998 )。

Changing the time zone to GMT: 将时区更改为GMT:

formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]

should fix the problem. 应该解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM