Human friendly date descriptions with NSDate on iOS

前端 未结 6 1689
忘了有多久
忘了有多久 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)
      }
    

提交回复
热议问题