Human friendly date descriptions with NSDate on iOS

亡梦爱人 提交于 2019-11-27 13:07:46

问题


I want to display NSDates in a "human-friendly way", such as "last week", or "a few days ago". Something similar to Pretty Time for Java.

What's the best way to do this, subclassing NSDateFormatter? Before I go and reinvent the wheel, is there already some library for this?


回答1:


This is the solution in 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)
  }



回答2:


On iOS 4 and later, use the doesRelativeDateFormatting property:

NSDateFormatter *dateFormatter = ...;
dateFormatter.doesRelativeDateFormatting = YES;



回答3:


Three20's NSDateAdditions:

https://github.com/pbo/three20/blob/master/src/Three20Core/Sources/NSDateAdditions.m

.. allows you to do that as well.

EDIT: In 2013, you really don't want to use Three20 anymore. Use Regexident's solution.




回答4:


Full code snippet for human readable dates in Xcode:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

    NSLocale *locale = [NSLocale currentLocale];
    [dateFormatter setLocale:locale];

    [dateFormatter setDoesRelativeDateFormatting:YES];



回答5:


A good date formatter is YLMoment, which is based on the popular moment.js.

It does format nice relative times.




回答6:


Use the DateTools (github/Cocoapods) timeAgoSinceNow function. Here's some sample output...

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"

The timeAgoSinceDate function is also handy.

DateTools supports many (human) languages and gives much better relative descriptions than NSDateFormatter's somewhat limited doesRelativeDateFormatting.



来源:https://stackoverflow.com/questions/6332298/human-friendly-date-descriptions-with-nsdate-on-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!