Home > Software design >  How to use DateComponent with new Foundation formatters?
How to use DateComponent with new Foundation formatters?

Time:07-12

I'm trying to use the DateComponentsFormatter with the new Foundation formatters. To format a date, I can do something like this:

Date.now.formatted(.dateTime.hour().minute().second())
// 5:03:17 PM

However, I'm trying to use this new API for using the DateComponentsFormatter:

let duration: TimeInterval = 0

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.minute, .second]
formatter.zeroFormattingBehavior = [.pad]

let formattedDuration = formatter.string(from: 0)
// 00:00

How can I use the new Foundation formatters API for DateComponentsFormatter to achieve this?

CodePudding user response:

AFAIK the formatted method for a time interval only works with Duration objects which needs to be initialized with a timeval:

let duration: TimeInterval = 125.0
let tmv = timeval(tv_sec: Int(duration), tv_usec: 0)
Duration(tmv)
    .formatted(.time(pattern: .hourMinuteSecond))  // "0:02:05"
Duration(tmv)
    .formatted(.time(pattern: .minuteSecond))      // "2:05"

or

Duration(
    secondsComponent: Int64(duration),
    attosecondsComponent: 0
).formatted(.time(pattern: .minuteSecond))  // "2:05"
  • Related