我想輸出日期(具有相對日期,例如Today,Yesterday等)和時間(尊重12/24小時在iOS設備上設置)例如NSDateFormatter - 在某些情況下不尊重12/24小時(am/pm)系統設置
- 今天下午5:48(在12小時模式時);和
- 今天17:48時(24小時模式)
配置NSFormatter像這樣(使用stringFromDate :)不起作用:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale: [NSLocale autoupdatingCurrentLocale]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle]; // doesn't respect am/pm setting on iOS device (grrr!)
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setDoesRelativeDateFormatting:YES]; // but does get relative dates
這給你相對日期,但默認爲語言環境的12/24設置,例如美國12小時,英國24小時。 (爲什麼蘋果認爲英國人喜歡24小時制鐘表,我不知道...)
我所採用的解決方案使用了兩個NSDateFormatters,一個用於日期和一個時間。看起來,當您使用NSDateFormatterNoStyle的dateStyle和NSDateFormatterShortStyle的timeStyle配置NSDateFormatter時,它確實遵守12/24小時設置。 (所以這只是當你有兩個日期和時間樣式設置,有麻煩。)
我已經包括我的工作,以防其他人有類似的問題。有沒有更簡單的方法來做到這一點?這個工作似乎有些尷尬,不清楚我應該如何確信它將在iOS的未來版本中繼續工作。
解決方法
- (NSString*) humanRelativeDateAndTimeAlt: (NSDate*) date;
{
NSDateFormatter* relativeDateFormatter = [[NSDateFormatter alloc] init];
[relativeDateFormatter setLocale: [NSLocale autoupdatingCurrentLocale]];
[relativeDateFormatter setTimeStyle:NSDateFormatterNoStyle]; // no time for this formatter
[relativeDateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setDoesRelativeDateFormatting:YES]; // relative dates
NSString* datePart = [[self relativeDateFormatter] stringFromDate:date];
NSDateFormatter* timeDateFormatter = [[NSDateFormatter alloc] init];
[timeDateFormatter setLocale:[NSLocale autoupdatingCurrentLocale]];
[timeDateFormatter setDateStyle: NSDateFormatterNoStyle]; // no date for this formatter
[timeDateFormatter setTimeStyle: NSDateFormatterShortStyle]; // does respect 12/24 hour setting
NSString* timePart = [timeDateFormatter stringFromDate:date];
int skipZero = 0; // extra code to remove leading zero if present
if ([[timePart substringToIndex:1] isEqualToString:@"0"]) skipZero = 1;
[relativeDateFormater release];
[timeDateFormatter release];
return [NSString stringWithFormat:@"%@ %@", datePart, [timePart substringFromIndex:skipZero]];
}
我確認了這個錯誤。它仍然存在於iOS 7中。在另一個線程上有關於此的廣泛討論:http://stackoverflow.com/questions/143075/nsdateformatter-am-i-doing-something-wrong-or-is-this-a-然而,錯誤 – 2013-10-01 06:36:34