最短的"time ago"

The shortest "time ago"

我创建了一个函数,它非常好地比较两个日期和 return 字符串的差异

extension Date {
    var shortTimeAgo: String {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.year,.month,.weekOfMonth,.day,.hour,.minute,.second]
        formatter.maximumUnitCount = 1
        formatter.unitsStyle = .short
        return formatter.string(from: self, to: Date())
    }
}

但它 return 的值类似于“35 秒”、“10 分钟”甚至“2 天 1 小时”

如何获得更短的值,如“35s”、“10m”和“2d”?

试试这个代码 -

extension Date {
    var shortTimeAgo: String {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.year,.month,.weekOfMonth,.day,.hour,.minute,.second]
        formatter.maximumUnitCount = 1
        formatter.unitsStyle = .abbreviated
        return formatter.string(from: self, to: Date())
    }
}

希望对您有所帮助!