get someone's age from birthdate swift in swift

main.swift
let birthdate = DateComponents(year: 1990, month: 9, day: 20).date! // example birthdate

let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: birthdate, to: Date())
let age = ageComponents.year!

print(age) // output: 31
260 chars
8 lines

Explanation:

  • Create a DateComponents instance containing the birthdate information
  • Use the Calendar.current instance to calculate the difference between the birthdate and the current date
  • Extract the year component from the difference using dateComponents(_:from:to:)
  • Access the year property of the resulting DateComponents instance to get the age in years.

gistlibby LogSnag