Can a dateComponent be formatted to display as hh: mm: ss?

I am trying to display a countdown in hh: mm: ss format, but since I am not outputting Date, but dateComponents, I cannot use formatter.dateFormat. Is there any way to format dateComponents?

I am currently getting output that looks like this:

hour: 5, minute: 12, second: 45

func nextEventCalculator() -> DateComponents {
    let now = Date()
    let calendar = Calendar.current
    let components = DateComponents(calendar: calendar, hour: 12, minute: 15)  // <- 12:15 pm
    let nextEvent = calendar.nextDate(after: now, matching: components, matchingPolicy: .nextTime)!

    let diff = calendar.dateComponents([.hour, .minute, .second], from: now, to: nextEvent)
    dateCountdownLabel.text = "\(diff)"
    return diff
}

      

+3


source to share


1 answer


Use DateComponentsFormatter

with unitsStyle

of .positional

:



let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
dateCountdownLabel.text = formatter.string(from: diff)

      

+2


source







All Articles