I created a function which very nice compare two dates and return difference as 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())
}
}
But it returns values like "35 sec", "10 min" or even "2 days 1 hr"
How to get even shorter values like "35s", "10m" and just "2d" ?
Try this code -
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())
}
}
Hope it helps!