Can I use RelativeDateTimeFormatter (or some other class) to create relative dates with multiple units?

Viewed 37

Apple's Foundation framework has the RelativeDateTimeFormatter class, which lets you describe time intervals relative to the current time. It will generate strings like "Two days ago."

Is it possible to generate strings like "Two days, seven hours and twenty-seven minutes ago" using a RelativeDateTimeFormatter or some other Foundation class? (Ideally with control over which units to use?

(The code below generates the string "yesterday".)

import Foundation

let formatter = RelativeDateTimeFormatter()
formatter.dateTimeStyle = .named
formatter.unitsStyle = .full

let outputString = formatter.localizedString(fromTimeInterval: -123456.789)

print(outputString)

You might think that using the localizedString(from:) form would work. (That version takes a DateComponents object.) You'd be wrong. It creates a similar, single-unit comparison:

let components = DateComponents(day: 2, hour: 3, minute: 7)
let outputString = formatter.localizedString(from: components)

That code creates the string "in 2 days."

0 Answers
Related