2013-11-25 133 views
0

我只有一些設備有問題NSDateFormatter返回null從服務器的日期格式是「13:05,2013年11月10日」。NSDateFormatter在某些設備上返回null

NSDate *Now = [NSDate serverDate]; 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"HH:mm, d MMM yyyy"]; 
    NSDate *LastLogin = [dateFormat dateFromString:DateString]; 

在模擬器和一些設備的工作原理

LastLogin 2013年10月5日0時36分00秒+0000 |現在,2013年11月25日14時50分51秒+0000

,但在某些設備上

LastLogin(空)|現在,2013年11月25日15點00分22秒+0000

+0

您遇到問題的設備可能會將其12/24時間設置與區域設置定義的相反。這在iOS中引發了「非技術性」(即,記錄的bug)。爲了解決這個問題,將語言環境設置爲「en_US_POSIX」。看到[這個線程](http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feature)。 –

回答

3

這個問題似乎是與區域設置,只需設置格式化的語言環境:

NSDate *Now = [NSDate serverDate]; 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
[dateFormat setDateFormat:@"HH:mm, d MMM yyyy"]; 
NSDate *LastLogin = [dateFormat dateFromString:DateString]; 
+0

謝謝你好,先生,祝你有個美好的一天:)因爲你是第一個人,所以我會標記你的答案。 –

+0

@KrisGeorgiev謝謝你)祝你有美好的一天 –

3

如果你沒有設定特定的語言環境,即使使用固定的日期格式,數字和日期也可能會有所不同。

The docs有這樣的說法;

如果您使用的是固定格式的日期,則應首先將日期格式化程序的區域設置爲適合固定格式的區域。在大多數情況下,要選擇的最佳語言環境是en_US_POSIX,該語言環境專門設計用於在不考慮用戶和系統偏好的情況下生成美國英語結果。

稍微擴展您的代碼;

NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; 
NSDate *Now = [NSDate serverDate]; 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setLocale:enUSPOSIXLocale]; 
[dateFormat setDateFormat:@"HH:mm, d MMM yyyy"]; 
NSDate *LastLogin = [dateFormat dateFromString:DateString]; 
相關問題