我创建了一个非常好的比较两个日期的函数,并将差异作为String
返回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())
}
}
但它返回的值如“35秒”,“10分钟”或甚至“2天1小时”
如何获得更短的值,如“35s”,“10m”和“2d”?
答案 0 :(得分:1)
试试这段代码 -
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())
}
}
希望它有所帮助!