cfi*_*her 13 cocoa cocoa-touch nsdate nsdateformatter
我希望以"人性化的方式"显示NSDates,例如"上周"或"几天前".类似于Pretty Time for Java的东西.
什么是最好的方法,子类化NSDateFormatter?在我去重新发明轮子之前,是否已经有了一些库?
Reg*_*ent 40
在iOS 4及更高版本中,使用doesRelativeDateFormatting属性:
NSDateFormatter *dateFormatter = ...;
dateFormatter.doesRelativeDateFormatting = YES;
Run Code Online (Sandbox Code Playgroud)
Three20的NSDateAdditions:
https://github.com/pbo/three20/blob/master/src/Three20Core/Sources/NSDateAdditions.m
..也允许你这样做.
编辑:在2013年,你真的不想再使用Three20了.使用Regexident的解决方案.
Xcode中人类可读日期的完整代码段:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSLocale *locale = [NSLocale currentLocale];
[dateFormatter setLocale:locale];
[dateFormatter setDoesRelativeDateFormatting:YES];
Run Code Online (Sandbox Code Playgroud)
这是 Swift 2 中的解决方案:
func formattedHumanReadable(date: NSDate) -> String {
let formatter = NSDateFormatter()
formatter.timeStyle = .NoStyle
formatter.dateStyle = .ShortStyle
formatter.doesRelativeDateFormatting = true
let locale = NSLocale.currentLocale()
formatter.locale = locale
return formatter.stringFromDate(date)
}
Run Code Online (Sandbox Code Playgroud)