2012-08-07 20 views
1

世界的專家你好,爲什麼NSDateFormatter在12小時的時間設置下會在24小時當地人返回NULL?

我遇到了一個很奇怪的問題:

我格式化表示從00-23以下方式時間(由谷歌服務返回的)的字符串:

(傳入的字符串可以說14,應該輸出無論是14:00或下午2:00,取決於用戶的本地)

+(NSString *) formatTime: (NSString *)timeToBeFormatted { 

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"HH"]; 
    NSDate *date = [[NSDate alloc] init]; 
    date = [dateFormat dateFromString:timeToBeFormatted]; 

    // Convert date object to desired output format 
    [dateFormat setTimeStyle:NSDateFormatterShortStyle]; 

    timeToBeFormatted = [dateFormat stringFromDate:date]; 
    return timeToBeFormatted; 
} 

一切都在所有的當地人工作正常全世界。

但是,只有當用戶將他的TIME格式設置爲12h時,默認值爲24h的本地格式化程序將返回NULL,僅用於12-23之間的值。非常奇怪,我會說!

例子: (NULL)格式化後12 12:00 AM 格式13 前前後

任何想法,爲什麼這可能發生?

謝謝!

回答

2

解決! (靈感來自上面的答案)..

爲了解決這個問題,我創建了一個特定的語言環境,然後使用這個語言環境來表達stringToDate。然後,我創建使用默認的用戶喜好另一個地區和使用語言環境的措辭.. dateBackToString

+(NSString *) formatTime: (NSString *)timeToBeFormatted 
{ 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 

//ADDED// 
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; 
[dateFormat setLocale:enUSPOSIXLocale]; 

[dateFormat setDateFormat:@"HH"]; 
NSDate *date = [[NSDate alloc] init]; 
date = [dateFormat dateFromString:timeToBeFormatted]; 

//ADDED// 
NSLocale *defualtLocale = [[NSLocale alloc] init]; 
[dateFormat setLocale:defualtLocale]; 

[dateFormat setTimeStyle:NSDateFormatterShortStyle]; 
timeToBeFormatted = [dateFormat stringFromDate:date]; 

return timeToBeFormatted; 
} 

我想它很昂貴的舊設備,但在ARC和它的作品強手機時代;)

+0

如果它應該接受答案真的幫助你。 – Devang 2012-08-09 09:53:56

+0

真棒解決方案! – Gabox 2014-03-07 18:09:02

+0

即使這已被假定爲問題的正確答案,但這隻適用於公曆。如果用戶使用其他日曆,如佛教,那麼這種解決方法將無法正常工作! – Bms270 2017-03-02 16:39:05

1

NSDateFormatter使用當前語言環境和時間設置來解析(並輸出)時間。如果您想使用特定的時間格式,請自行設置日期格式化程序的區域設置。

dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 

此外,在創建日期格式是昂貴,如果你調用這個函數往往你應該緩存的日期格式在一個靜態變量。

+0

謝謝Nilsson,但是對我來說,使用當前用戶本地輸出是非常重要的,因爲我的客戶遍佈全球。因此,我無法爲每個人創建特定的本地。 – Sheni 2012-08-07 12:00:22

1

我在一段時間之前也面臨這個問題。

使用以下代碼根據您的需要合成日期。

+(NSDate *)getGMTDateToView:(NSDate *) availableDate formatter:(NSDateFormatter *)timeFormat { 


    NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; 
    [timeFormat setLocale:enUSPOSIXLocale]; 


    NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; 
    NSTimeInterval gmtTimeInterval = [availableDate timeIntervalSinceReferenceDate] + timeZoneOffset; 

    [timeFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 

    [timeFormat setDateStyle:NSDateFormatterShortStyle]; 
    [timeFormat setTimeStyle:NSDateFormatterShortStyle]; 

     enUSPOSIXLocale = nil; 
     return [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval]; 

} 

我發現上面的代碼從蘋果公司的文件之一(我已經修改(點點),它按我的需要),但無法立即找到此鏈接。

相關問題