Learn Courses My Dashboard

Calculating age from date of birth

It seems like this would be a very common operation that an app would need but I am having a difficult time finding any up to date information about how to calculate a person’s age from their DOB.

Any suggestions?

Todd

Hey @toddrmyers11

Maybe this article can help you!

Best way to do it would be to use date components

import Foundation

let cal = Calendar.current

let now = Date.now
let components = DateComponents(calendar: .current, year: 1980, month: 07, day: 11)
let bday = cal.date(from: components)!

let age = cal.dateComponents([.year, .month], from: bday, to: now)
print(age)
//year: 41 month: 8 isLeapMonth: false 

So somebody born on 11 July 1980 would be 41 years and 8 months old as of today, 5 April 2022.

Thanks. This works in the Playground but why doesn’t it work when I put it in a struct in a file in my project?

Todd

Because you can’t have code like that in a struct but outside of a method or a computed property. You can use a DateComponents as the parameter or break it up into separate params for year, month, day.

Something like this:

func calculateAge(from birthdate: DateComponents) -> DateComponents {
    let cal = Calendar.current
    
    let now = Date.now
    let bday = cal.date(from: birthdate)!
    
    return cal.dateComponents([.year, .month], from: bday, to: now)
}

Or this:

func calculateAge(year: Int, month: Int, day: Int) -> DateComponents {
    let cal = Calendar.current
    
    let now = Date.now
    let components = DateComponents(calendar: .current, year: year, month: month, day: day)
    let bday = cal.date(from: components)!
    
    return cal.dateComponents([.year, .month], from: bday, to: now)
}