One of our apps has some failing unit tests that I traced back to a change in the way Calendar.date(from:) works on iOS 18 beta (22A5307d) as compared to earlier versions. The simple demo unit test below passes in iOS 17.5 and fails in 18 beta 3. I did not test this in other beta versions.
import XCTest
final class DateComponentsMath_Tests: XCTestCase {
func testAddingWeek() throws {
var components = DateComponents(
year: 2024,
weekOfYear: 1,
yearForWeekOfYear: 2024
)
let date1 = Calendar.current.date(from: components)!
// add a few weeks to the components
components.weekOfYear = components.weekOfYear! + 5
let date2 = Calendar.current.date(from: components)
XCTAssertNotEqual(date1, date2, "We added five weeks to the components so this should not result in the same date")
}
}
It appears that in iOS 18 (22A5307d), year, weekOfYear, and yearForWeekOfYear are no longer enough to uniquely specify a date. With those three values, Calendar.date(from:) always returns January 1 of the specified year. In earlier versions of iOS this was not the case.
I submitted this as FB14323984
I submitted this as FB14323984
Thanks for filing that. Foundation is getting a serious makeover this year, so I’m not super surprised to see an issue like this. Filing a bug is definitely the right path forward here.
However, I’m curious about the code you posted. You specify both the year
and yearForWeekOfYear
components, which seem contradictory. The year
component is used when you’re doing year/month/day calculations and the yearForWeekOfYear
component is used when you’re doing year/week-of-year/day-within-week calculations. Apply both is weird, and you could imagine it causing problems because some days at the beginning and end of the year can have different values for these components.
So, what happens if you drop the year
component from your test?
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"