Thursday, October 29, 2026
HomeiOS Developmentios - Utilizing DateComponents distinction to get age - Bug with Leap...

ios – Utilizing DateComponents distinction to get age – Bug with Leap Years?

[ad_1]

Right now I encountered a failing pipeline check in a date technique used to calculate the age of an individual.

Apple’s DateComponents comparability fails from what I can inform.

Given Dates (YYYY-MM-DD):

2004-02-29 as Birthday
2022-02-28 (Right now)

We anticipated a distinction of 17 years and 12 months. As 2004 had three hundred and sixty six days (intercalary year) that ought to not equal 18 years.

Instance Code utilized in Playground to breed:

import Basis

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.present

calendar.dateComponents([.year, .month, .day], from: date1, to: date2) // 18 yrs: flawed
calendar.dateComponents([.year, .month, .day], from: date2, to: date1) // 17 yrs, 11 months, 28 days: appropriate, however unfavourable

calendar.dateComponents([.year, .day], from: date1, to: date2) // 18 yrs: flawed
calendar.dateComponents([.year, .day], from: date2, to: date1) // 17 yrs, 12 months: appropriate, however unfavourable

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

So, I’m questioning if this can be a bug, a recognized bug (Suggestions/Radar anybody?) or is my assumption flawed?

Result in Playground

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments