I am seeing a weird behavior of the date formatter (Full code is below).
When run, this will give the following output:
57: 1 month, 3 weeks, 5 days
58: 1 month, 3 weeks, 6 days
59: 2 months
60: 2 months, 1 day
61: 2 months
62: 2 months, 1 day
63: 2 months, 2 days
So both 59 days and 61 days are 2 months, and both 60 and 62 days are 2 months and 1 day.
This of course is especially weird because this means, 2 months also comes after 2 months and a day.
Can someone explain to me what is going on here?
import Foundation
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
let calendar = Calendar(identifier: .gregorian)
let today = calendar.date(from: DateComponents(year: 2025, month: 7, day: 26))!
for day in 57...63 {
let startDate = calendar.date(byAdding: .day, value: -day, to: today)!
let components = calendar.dateComponents([.day, .weekOfMonth, .month,. year], from: startDate, to: today)
let result = formatter.string(from: components)!
print ("\(String(format: "%3d", day)): \(result)")
}
Thank you for your replies, I think I found the answer myself. The issue seems to be that I am formatting from the components. If I use string(from: to:), then the output is as I would expect it!
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.year, .month, .weekOfMonth, .day]
let result = formatter.string(from: startDate, to: endDate)