在iOS上使用NSDate的人类友好的日期描述

| 我想以“人类友好的方式”显示NSDates,例如“上周”或“几天前”。与Java的Pretty Time类似。 子类化NSDateFormatter的最佳方法是什么?在我重新发明轮子之前,已经有一些图书馆了吗?     
已邀请:
        这是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)
  }
    
        在iOS 4和更高版本上,使用dosRelativeDateFormatting属性:
NSDateFormatter *dateFormatter = ...;
dateFormatter.doesRelativeDateFormatting = YES;
    
        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];
    
        YLMoment是一个很好的日期格式化程序,它基于流行的moment.js。 它确实格式化了很好的相对时间。     
        使用DateTools(github / Cocoapods)
timeAgoSinceNow
函数。这是一些示例输出...
NSDate.init(timeIntervalSinceNow:-3600).timeAgoSinceNow()         \"An hour ago\"
 NSDate.init(timeIntervalSinceNow:-3600*24).timeAgoSinceNow()      \"Yesterday\"
 NSDate.init(timeIntervalSinceNow:-3600*24*6).timeAgoSinceNow()    \"6 days ago\"
 NSDate.init(timeIntervalSinceNow:-3600*24*7*3).timeAgoSinceNow()  \"3 weeks ago\"
 NSDate.init(timeIntervalSinceNow:-3600*24*31*3).timeAgoSinceNow() \"3 months ago\"
timeAgoSinceDate
功能也很方便。 DateTools支持许多(人类)语言,并且比
NSDateFormatter
略有限制的
doesRelativeDateFormatting
提供了更好的相对描述。     

要回复问题请先登录注册