如何格式化日期,如“5 分钟”、“1 小时”、"Yesterday"、“1 周前”?

How to format a date like "5 min", "1 hour,", "Yesterday", "1 Week ago"?

我正在尝试获取类似于 facebook post date/time 的内容。比如 1 分钟、1 小时、昨天、一周前等

这是我用来获取此格式的函数:(Oct-22 17:28 PM)

func convertTime(serverTime: Double)  -> String {
    let serverTime = serverTime
    let date = Date(timeIntervalSince1970: serverTime)
    let dateFomatter = DateFormatter()
    dateFomatter.dateFormat = "MMM-dd HH:mm a"
    let strDate = dateFomatter.string(from: date)
    print("This is the post's date: \(strDate)")

    return strDate
}

试试这个代码

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let before = dateFormatter.date(from: "2017-10-23 10:28:17")!

//getting the current time
let now = Date()

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.zeroFormattingBehavior = .dropAll
formatter.maximumUnitCount = 1 
formatter.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute]
formatter.includesApproximationPhrase = true 


let formatString = NSLocalizedString("%@ ago", comment: "e.g. '2 hours ago'")

let timeString = formatter.string(from: before, to: now)