NSDateFormatter和日期转换无效

Cy.*_*Cy. 2 cocoa cocoa-touch objective-c ios-simulator

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

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

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

当区域设置为US(我回到正确的日期)时,该方法有效,但是当我将区域(在Settings-> General-> International中)更改为西班牙或其他区域时(此时我得到的回报为零) ).

- (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;  
}
Run Code Online (Sandbox Code Playgroud)

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

小智 12

问题似乎是您的区域设置不是"en-US",因此日期格式化程序不会使用提供的en-US格式解析字符串.虽然可能有一个更优雅的通用解决方案,但是对original_ateFormatter执行en_US的setLocale可以用作解决问题的解决方法.

正如您已经尝试过的代码:

[originalDateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
Run Code Online (Sandbox Code Playgroud)