【问题标题】:NSDateFormatter and date conversion not workingNSDateFormatter 和日期转换不起作用
【发布时间】:2011-01-11 22:19:01
【问题描述】:

我正在为 iPhone 开发一个应用程序,我需要将 XML 提要中的日期转换为 HH:MM 格式。

我有以下方法不起作用,我不知道我做错了什么。

例如,timeToConvert 字符串为:“Mon, 01 Feb 2010 21:55:00 +0100”(不带引号)

当地区设置为美国时该方法有效(我得到正确的日期),但当我将地区(在设置->常规->国际中)更改为西班牙或其他地区时(在这种情况下,我返回零)。

- (id)timeConvertToHHMM:(NSString *)timeToConvert {

    NSString *newPubDate = timeToConvert;
    //Let's remove any rubbish from the code
    newPubDate = [newPubDate stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //create formatter and format to convert the XML string to an NSDate
    NSDateFormatter *originalDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [originalDateFormatter setDateFormat:@"EEE, d MMM yyyy H:mm:ss z"];
    //run the string through the formatter
    NSDate *formattedDate = [[NSDate alloc] init];
    formattedDate = [originalDateFormatter dateFromString:newPubDate];
    //Let's now create another formatter to take the NSDate and convert format it to Hours and minutes
    NSDateFormatter *newDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [newDateFormatter setDateFormat:@"HH:mm"]; // 24H clock set
    // And let's convert it back to a readable string
    NSString *calcHHMM = [newDateFormatter stringFromDate:formattedDate];
    NSLog(@"CalcHHMM: %@", calcHHMM);
    return calcHHMM;  
}

任何关于为什么这不起作用的提示,只返回 NULL 将非常受欢迎。

【问题讨论】:

  • 您收到错误消息还是返回错误的时间?
  • 只返回 NULL... 看起来直到 formattedDate = [originalDateFormatter dateFromString:newPubDate];
  • 该代码对我有用,除了它返回转换为我当地时区的时间。当您将示例字符串传递给 formattedDate 时,它​​的值是多少?
  • 好的,由于某种原因,它无法使用您在 originalDateFormatter 中提供的格式解析字符串。不知道为什么它对我有用,但您可能必须在格式化程序上执行 setLocale?此外,当您删除格式末尾的“z”时,它将按原样返回小时而不转换为本地时间。
  • 看起来设置中的 REGION 与它有关。当我将其设置为美国时,它可以工作,但是如果我将其设置为西班牙(例如),它会停止工作并返回 NULL... 我尝试添加:[originalDateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@ "es_ES"] 自动释放]];但不起作用...

标签: objective-c cocoa cocoa-touch ios-simulator


【解决方案1】:

问题似乎是您的区域设置不是“en-US”,因此日期格式化程序不会使用提供的 en-US 格式解析字符串。虽然可能有更优雅、更通用的解决方案,但可以将 originalDateFormatter 上的 setLocale 设置为 en_US 来解决问题。

正如您已经在代码中尝试过的那样:

[originalDateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];

【讨论】:

    【解决方案2】:

    我遇到了完全相同的问题。我的问题是我的初始日期字符串只有一个毫秒字符:

    示例:2011-02-06 08:13:22:1

    并且正在使用这种格式进行解析:[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    iPhone 模拟器很宽容,并成功地以毫秒为单位解析了日期,但是在构建到我的 iphone 时却没有。
    将格式化程序更改为:[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"]; 解决了问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-10
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 2018-02-05
      • 2017-07-31
      相关资源
      最近更新 更多