tejasree vangapalli
tejasree vangapalli

Reputation: 89

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 tried below logic but, didn't work.


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

Upvotes: 1

Views: 1308

Answers (1)

Paulw11
Paulw11

Reputation: 114828

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)
}

Upvotes: 4

Related Questions