TruMan1
TruMan1

Reputation: 36158

Format integer to minutes with new Foundation formatters?

I'm trying to format an integer to display it as minutes, but I can't get the syntax right and the docs are still light on this. This is what I'm trying:

let value: Int = 20
Text(value.formatted(.components(style: .abbreviated, fields: [.minute])))
// Compile error: Instance method 'formatted' requires the types 'Int' and 'Date.ComponentsFormatStyle.FormatInput' (aka 'Range<Date>') be equivalent

I'm trying to display: 20 min. How can this be done using the new Foundation formatters improvements from WWDC 2021?

I can do this the old way like this:

static let formatter: DateComponentsFormatter = {
    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .short
    formatter.allowedUnits = [.minute]
    return formatter
}()

Self.formatter.string(for: DateComponents(minute: value))

Upvotes: -1

Views: 257

Answers (1)

to format an integer you need a NumberFormatter. Or you could just do:

Text("\(value) min")

Upvotes: 0

Related Questions