我可以让 RelativeDateTimeFormatter 显示更多单位,例如年、月和日吗?
Can I make RelativeDateTimeFormatter display more units such year, month and day?
这是我的代码:
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
是 1 year ago
,而我希望它是 1 year, 11 months, 1 day ago
,这样更准确
我可以让 RelativeDateTimeFormatter 显示更多单位,例如年月日,以便它 returns 1 year, 11 months, 1 day ago
而不是 1 year ago
吗?
另一个选择是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)"
}
这是我的代码:
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
是 1 year ago
,而我希望它是 1 year, 11 months, 1 day ago
,这样更准确
我可以让 RelativeDateTimeFormatter 显示更多单位,例如年月日,以便它 returns 1 year, 11 months, 1 day ago
而不是 1 year ago
吗?
另一个选择是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)"
}