【问题标题】:NSString to NSDate issue IOS7NSString 到 NSDate 问题 IOS7
【发布时间】:2013-08-10 13:20:08
【问题描述】:

我正在使用以下代码将NSString 转换为NSDate

NSDate *date = [NSDate convertStringToDate:strDate andFormatter:@"MM dd"];

+ (NSDate *)convertStringToDate:(NSString *)dateString andFormatter:(NSString *)formatter
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    // this is imporant - we set our input date format to match our input string
    // if format doesn't match you'll get nil from your string, so be careful
    [dateFormatter setDateFormat:formatter];

    dateFormatter.timeZone = [NSTimeZone systemTimeZone];

    return [dateFormatter dateFromString:dateString];
}

NSString 是@"07 15"。但我的 NSDate 是nil。在模拟器上很好,但在 iOS7 设备上它是 nil。

你有什么建议吗?

【问题讨论】:

  • 您设备上设置的时区是否与您计算机上设置的时区相同?如果NSDateformatter dateFromString 转换失败,它将返回 nil。

标签: iphone nsstring nsdate nsdateformatter ios7


【解决方案1】:

如果您的代码在 iOS 6 中运行,那么这可能只是 iOS 7 中的一个错误。如果您认为是这种情况,请务必提交错误报告。

如果它在 iOS 6 中不起作用,那么可能是一个月和一天不足以指定日期。尝试添加年份,看看你是否得到了一个有效的日期。

请注意,有关 iOS 7 的问题应发布到 Apple 的开发者论坛,而不是此处。

【讨论】:

    【解决方案2】:

    您可能需要像这样设置语言环境:

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    

    我解决了这个问题,包括格式化程序的语言环境。 希望这会有所帮助。

    【讨论】:

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