Home > Back-end >  Can I make RelativeDateTimeFormatter display more units such year, month and day?
Can I make RelativeDateTimeFormatter display more units such year, month and day?

Time:05-21

Here's my code:

let startDate = Calendar.current.date(from: DateComponents(year: 2022, month: 5, day: 1)) ?? .now
let endDate = Calendar.current.date(from: DateComponents(year: 2020, month: 6, day: 2)) ?? .now

let dateComponents = Calendar.current.dateComponents([.year, .month, .day], from: startDate, to: endDate)
let relativeDateTimeFormatter = RelativeDateTimeFormatter()
let dateRemainingText = relativeDateTimeFormatter.localizedString(from: dateComponents)

dateRemainingText is 1 year ago, while I would like it to be 1 year, 11 months, 1 day ago, which is more accurate

Can I make RelativeDateTimeFormatter display more units such year, month and day, so that it returns 1 year, 11 months, 1 day ago instead of 1 year ago?

CodePudding user response:

An alternative is DateComponentsFormatter

let startDate = Calendar.current.date(from: DateComponents(year: 2022, month: 5, day: 1)) ?? .now
let endDate = Calendar.current.date(from: DateComponents(year: 2020, month: 6, day: 2)) ?? .now

let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.year, .month, .day]
dateComponentsFormatter.unitsStyle = .full
var dateRemainingText = dateComponentsFormatter.string(from: startDate, to: endDate)!
if dateRemainingText.hasPrefix("-") {
    dateRemainingText = "\(dateRemainingText.dropFirst()) ago"
} else {
    dateRemainingText = "in \(dateRemainingText)"
}
  • Related