Swift – Calculate Age from a Given Birthdate

In this tutorial, we will learn how to calculate age from a given birthdate in Swift. We will use the Calendar class to compute the difference between the current date and the birthdate, and handle edge cases like leap years and incomplete dates.


Calculating Age in Swift

To calculate the age, we find the difference in years between the birthdate and the current date. The Calendar class provides the dateComponents(_:from:to:) method, which allows us to compute differences in various units such as years, months, and days.

Here’s a basic example:

</>
Copy
import Foundation

let calendar = Calendar.current
let birthdateComponents = DateComponents(year: 1990, month: 5, day: 15)
let birthdate = calendar.date(from: birthdateComponents)!

let currentDate = Date()
let ageComponents = calendar.dateComponents([.year], from: birthdate, to: currentDate)

if let age = ageComponents.year {
    print("Age: \(age) years")
}

Explanation:

  • DateComponents(year: 1990, month: 5, day: 15): Specifies the birthdate.
  • calendar.date(from: birthdateComponents): Converts the components into a Date object.
  • calendar.dateComponents([.year], from: birthdate, to: currentDate): Calculates the difference in years between the birthdate and the current date.

Adding More Detail: Months and Days

You can extend the calculation to include months and days by specifying them in the dateComponents method. Here’s how:

</>
Copy
let detailedAgeComponents = calendar.dateComponents([.year, .month, .day], from: birthdate, to: currentDate)

if let years = detailedAgeComponents.year,
   let months = detailedAgeComponents.month,
   let days = detailedAgeComponents.day {
    print("Age: \(years) years, \(months) months, \(days) days")
}

This provides a detailed breakdown of the age, including the number of years, months, and days.

Handling User Input for Birthdate

To allow the user to input their birthdate, we can use a string format and parse it using DateFormatter. Here’s an example:

</>
Copy
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

if let birthdate = dateFormatter.date(from: "1990-05-15") {
    let ageComponents = calendar.dateComponents([.year, .month, .day], from: birthdate, to: currentDate)
    if let years = ageComponents.year, let months = ageComponents.month, let days = ageComponents.day {
        print("Age: \(years) years, \(months) months, \(days) days")
    }
} else {
    print("Invalid birthdate format")
}

In this example, the program calculates age for a birthdate entered in the format yyyy-MM-dd.

Complete Swift Program

Here’s the complete Swift program to calculate age from a given birthdate:

main.swift

</>
Copy
import Foundation

// Function to calculate age from birthdate
func calculateAge(from birthdateString: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    
    guard let birthdate = dateFormatter.date(from: birthdateString) else {
        return "Invalid birthdate format"
    }
    
    let calendar = Calendar.current
    let currentDate = Date()
    let ageComponents = calendar.dateComponents([.year, .month, .day], from: birthdate, to: currentDate)
    
    if let years = ageComponents.year, let months = ageComponents.month, let days = ageComponents.day {
        return "Age: \(years) years, \(months) months, \(days) days"
    } else {
        return "Could not calculate age"
    }
}

// Test cases
print(calculateAge(from: "1990-05-15"))
print(calculateAge(from: "2000-12-01"))
print(calculateAge(from: "invalid-date"))

Output:

Age: 34 years, 6 months, 6 days
Age: 23 years, 11 months, 20 days
Invalid birthdate format
Program ended with exit code: 0

This program is versatile, supporting both detailed age calculation and validation of the birthdate format. It handles invalid input gracefully and works with leap years and other edge cases.

Swift Program to Calculate Age from a Given Birthdate