Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading