'Using DateComponents difference to get age - Bug with Leap Years?

Today I encountered a failing pipeline test in a date method used to calculate the age of a person.

Apple's DateComponents comparison fails from what I can tell.

Given Dates (yyyy-MM-dd):

2004-02-29 as Birthday
2022-02-28 (Today)

We expected a difference of 17 years and 365 days. As 2004 had 366 days (leap year) that should not equal 18 years.

Example Code used in Playground to reproduce:

import Foundation

let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]

let date1 = dateFormatter.date(from: "2004-02-29T00:00:00.000Z")!
let date2 = dateFormatter.date(from: "2022-02-28T00:00:00.000Z")!

var calendar = Calendar.current

calendar.dateComponents([.year, .month, .day], from: date1, to: date2) // 18 yrs: wrong
calendar.dateComponents([.year, .month, .day], from: date2, to: date1) // 17 yrs, 11 months, 28 days: correct, but negative

calendar.dateComponents([.year, .day], from: date1, to: date2) // 18 yrs: wrong
calendar.dateComponents([.year, .day], from: date2, to: date1) // 17 yrs, 365 days: correct, but negative

Apple Swift version 5.5.2 (swiftlang-1300.0.47.5 clang-1300.0.29.30)

So, I am wondering if this is a bug, a known bug (Feedback/Radar anyone?) or is my assumption wrong?

Result in Playground



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source