Human friendly date descriptions with NSDate on iOS
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开发者_如何学JAVA go and reinvent the wheel, is there already some library for this?
On iOS 4 and later, use the doesRelativeDateFormatting property:
NSDateFormatter *dateFormatter = ...;
dateFormatter.doesRelativeDateFormatting = YES;
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.
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];
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)
}
A good date formatter is YLMoment, which is based on the popular moment.js.
It does format nice relative times.
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
.
精彩评论