Human friendly date descriptions with NSDate on iO

2019-01-22 15:04发布

问题:

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.