swifttime-format

How to format time in "h m s" format in swift using `Duration.TimeFormatStyle`


I wrote an extension of TimeInterval which returns a string in the format "h m s". For example, 5 hours, 33 minutes and 15 seconds would be written as "5h 33m 15s". This is the code:

extension TimeInterval {
  init(hours: Int, minutes: Int, seconds: Int) {
    self = Double(hours * 3600 + minutes * 60 + seconds)
  }

  func toString() -> String {
    let totalSeconds = Int(self)
    let hours = totalSeconds / 3600
    let minutes = (totalSeconds % 3600) / 60
    let seconds = totalSeconds % 60

    if hours >= 1 {
      return "\(hours)h \(minutes)m"
    } else if minutes >= 1 {
      return "\(minutes)m \(seconds)s"
    } else {
      return "\(seconds)s"
    }
  }
}

I'd like to achieve this same functionality using Apple's Duration.TimeFormatStyle fashion. For example,I can do the following:

let style = Duration.TimeFormatStyle(pattern: .hourMinuteSecond)
var formattedTime = Duration.seconds(someInterval).formatted(style)

which I think is better practice than writing a toString() function as an extension of TimeInterval, but I'm not sure how to go about creating this style. Any guidance would be great.


Solution

  • What you are looking for is called Duration UnitsFormatStyle units with narrow width:

    let duration: Duration = .seconds(15 + 33 * 60 + 5 * 3600)
    let string = duration.formatted(.units(width: .narrow)) // "5h 33m 15s"