I have a time interval, say, 12600, which is equivalent to 3 hours 30 minutes. How could I format any such time interval so that only the highest part of the interval (for example in this case figure, the hours) is kept and have the correct locale abbreviation be appended to the number. For example 10m (10 minutes), 3d (3 days), 1y (1 years).
EDIT: Here are some examples:
Time interval in: 90000 Whole string: 1d String out: 1d Time interval in: 900 Whole string: 15m String out: 15m Time interval in: 13500 Whole String: 3h 45m String out: 4h
As a general rule, apply the normal rounding rules (3.4 rounds down, 3.6 rounds up).
If you want a time interval different from now, use the constructor Date(timeIntervalSinceNow:) Gives you a date one minute from now 2016-11-10 11:59:36 +0000 . If you want a date where you add or subtract a time interval, use Date(timeInterval:since:) Gives us a date an hour from now: 2016-11-10 12:59:36 +0000 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With