DateComponentsFormatter - 相同的日期,不同的结果

DateComponentsFormatter - same dates, different results

为什么 dateRemainingText2 给出的结果与 dateRemainingText 不同?
显然dateRemainingText2是错误的

这是我的代码:

import Foundation

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)! // -1 year, 10 months, 29 days
let dateComponents = Calendar.current.dateComponents([.year, .month, .day], from: startDate, to: endDate)
var dateRemainingText2 = dateComponentsFormatter.string(from: dateComponents) // -1 year, 11 months, 1 day

DateComponentsFormatter.string(from:to:)DateComponentsFormatter.string(from:) 是不同的方法,所以它们可以做不同的事情。

从一些实验中,我们可以看到 string(from:) 输出一个字符串,该字符串描述传入的 DateComponent 中所有日期组件的 sum .

这只是 碰巧string(from:to:) 的输出相同,在大多数情况下分量都是正的。

示例:

// 1 month + 7 days
var dateComponents = DateComponents()
dateComponents.month = 1
dateComponents.day = 7
// 1 month, 7 days
print(dateComponentsFormatter.string(from: dateComponents)!)

// 7 days - 1 month
dateComponents.month = -1
dateComponents.day = 7
// -24 days
print(dateComponentsFormatter.string(from: dateComponents)!)

// 1 month - 7 days
dateComponents.month = 1
dateComponents.day = -7
// 24 days
print(dateComponentsFormatter.string(from: dateComponents)!)

// 1 month + 30 days
// note that adding 1 month, it's February, and there are only 28 days
dateComponents.month = 1
dateComponents.day = 30
// 2 months, 2 days
print(dateComponentsFormatter.string(from: dateComponents)!)

// -10 months - 30 days
// note that after subtracting 10 months, it is March of the previous year, 
// which also happens to be a leap year, so February has 29 days
// Subtracting 30 days from that will bring us to January, with one day left
// which is, where the extra month and day came from
dateComponents.month = -10
dateComponents.day = -30
// -11 months, 1 day
print(dateComponentsFormatter.string(from: dateComponents)!)

// -1 year - 10 months - 30 days
// similar to above, except not a leap year
// so we have 2 days left after subtracting from a 28-day February.
dateComponents.year = -1
dateComponents.month = -10
dateComponents.day = -30
// -1 year, 11 months, 2 days
print(dateComponentsFormatter.string(from: dateComponents)!)

最后一个案例中使用的 DateComponents 就是您代码中的 Calendar.dateComponents(_:from:to:)

另一方面,string(from:to) 是格式化两个日期之间的时间段的指定方法。