How to format time intervals for user display (social network like) in swift?
If you are targeting newer OS versions (iOS 13.5+, OS X 10.15+), you can use RelativeDateTimeFormatter
:
let formatter = RelativeDateTimeFormatter()
formatter.dateTimeStyle = .named
for d in [-12600.0, -90000.0, -900.0, 13500.0] {
let str = formatter.localizedString(fromTimeInterval: d)
print("\(d): \(str)")
}
// Output
-12600.0: 3 hours ago
-90000.0: yesterday
-900.0: 15 minutes ago
13500.0: in 3 hours
For older OS versions, use DateComponentFormatter
, available since iOS 8:
func format(duration: TimeInterval) -> String {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.day, .hour, .minute, .second]
formatter.unitsStyle = .abbreviated
formatter.maximumUnitCount = 1
return formatter.string(from: duration)!
}
for d in [12600.0, 90000.0, 900.0, 13500.0] {
let str = format(duration: d)
print("\(d): \(str)")
}
This prints:
12600.0: 4h
90000.0: 1d
900.0: 15m
13500.0: 4h
Just in case anyone wants it.. Swift 4
extension TimeInterval {
func format(using units: NSCalendar.Unit) -> String? {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = units
formatter.unitsStyle = .abbreviated
formatter.zeroFormattingBehavior = .pad
return formatter.string(from: self)
}
}
Example usage:
let value:TimeInterval = 12600.0
print("\(value.format(using: [.hour, .minute, .second])!)")
and the result will be:
3h 30m 0s