Human friendly date descriptions with NSDate on iOS

前端 未结 6 1674
忘了有多久
忘了有多久 2020-12-14 10:40

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

相关标签:
6条回答
  • 2020-12-14 10:59

    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)
      }
    
    0 讨论(0)
  • 2020-12-14 11:00

    On iOS 4 and later, use the doesRelativeDateFormatting property:

    NSDateFormatter *dateFormatter = ...;
    dateFormatter.doesRelativeDateFormatting = YES;
    
    0 讨论(0)
  • 2020-12-14 11:02

    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.

    0 讨论(0)
  • 2020-12-14 11:04

    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];
    
    0 讨论(0)
  • 2020-12-14 11:16

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

    It does format nice relative times.

    0 讨论(0)
  • 2020-12-14 11:18

    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.

    0 讨论(0)
提交回复
热议问题