Calendar.nextDate(after:matching:matchingPolicy:) doesn’t work reliably for dates in February

Originator:dk
Number:rdar://37389859 Date Originated:February 9 2018
Status:Duplicate of 35883601 Resolved:
Product:iOS + SDK Calendar Product Version:iOS 11.2
Classification:Bug Reproducible:Always
 
Summary: 
Calling `nextDate(after: date, matching: DateComponents(day: 1), matchingPolicy: .nextTime)` on a calendar instance returns invalid result for dates in February.

Steps to Reproduce:
let calendar = Calendar(identifier: .gregorian)
let date = calendar.date(from: DateComponents(year: 2017, month: 2, day: 2))!
calendar.nextDate(after: date, matching: DateComponents(day: 1), matchingPolicy: .nextTime)

Expected Results:
Resulting date should be March 1, 2017. This works as expected for all other months.
The result is also correct if the components we pass in are not the first day of the month. E.g. `nextDate(after: date, matching: DateComponents(day: 2), matchingPolicy: .nextTime)` works just fine.

Actual Results:
Resulting date is February 1, 2020 in the example above. The year is actually always next leap-year after the date we pass in.
The same bug is affecting `date(bySetting: .day, value: 1, of: date)` method for the dates in February.

Version/Build:
Xcode Version 9.2 (9C40b)

Configuration:
The same behavior is observed in Playgrounds and iOS app on iOS 11.2.

Attached Playground:

import UIKit

let calendar = Calendar(identifier: .gregorian)
let firstDayOfMonth = DateComponents(day: 1)

let dateInFebruary = calendar.date(from: DateComponents(year: 2017, month: 2, day: 2))!
calendar.nextDate(after: dateInFebruary, matching: firstDayOfMonth, matchingPolicy: .nextTime)

let dateInMarch = calendar.date(from: DateComponents(year: 2017, month: 3, day: 2))!
calendar.nextDate(after: dateInMarch, matching: firstDayOfMonth, matchingPolicy: .nextTime)

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!