2010-02-01 45 views
2

我正在爲iPhone開發一個應用程序,我需要將XML Feed中的日期轉換爲HH:MM格式。NSDateFormatter和日期轉換不起作用

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

作爲一個例子,timeToConvert字符串是:「星期一,2010年2月1日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會更受歡迎任何暗示。

+0

您是否收到錯誤或是錯誤時間? – DyingCactus 2010-02-01 22:39:21

+0

只返回NULL ...看起來像所有的作品,直到 formattedDate = [originalDateFormatter dateFromString:newPubDate]; – 2010-02-01 22:49:12

+0

該代碼適用於我,但它返回轉換爲本地時區的時間。當你將它傳遞給示例字符串時,formattedDate的值是多少? – DyingCactus 2010-02-01 22:52:56

回答

12

問題似乎是您的區域設置不是「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"];解決了該問題。