Human friendly date descriptions with NSDate on iOS

前端 未结 6 1676
忘了有多久
忘了有多久 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 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.

提交回复
热议问题