Search code examples
iosswift5date-formattimezone-offsetdateformatter

How to format time interval offset from 00:00 in HH:MM using DateComponentsFormatter


I have a value in milliseconds that I want to display in HH:MM format

Example:

  • I have input given as 0 and output should be 00:00
  • If input is 3600000, output I need is 01:00

I tried below logic but, didn't work.


    func secondsToHourMinFormat(time: TimeInterval) -> String {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.hour, .minute]
        return formatter.string(from: time) 
    }


Solution

  • Your code is almost right, you just have a couple of omissions.

    1. A TimeInterval is in seconds are you are passing milliseconds, so you need to divide by 1000
    2. You need to set the .zeroFormattingBehaviour to .pad so that you don't get zero suppression in your output
    3. You need to handle the optional return from string(from:) somehow; I have changed your function to return a String?
    func secondsToHourMinFormat(time: TimeInterval) -> String? {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.hour, .minute]
        formatter.zeroFormattingBehavior = .pad
        return formatter.string(from: time/1000)
    }