
For a new application I’m working on I needed to capture the birth date of a user and validate if they are old enough to use the app.
Below is a simple method in Swift to return the age of a user after passing in the users birthday.
func calculateAge (birthday: NSDate) -> NSInteger { var userAge : NSInteger = 0 var calendar : NSCalendar = NSCalendar.currentCalendar() var unitFlags : NSCalendarUnit = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay var dateComponentNow : NSDateComponents = calendar.components(unitFlags, fromDate: NSDate.date()) var dateComponentBirth : NSDateComponents = calendar.components(unitFlags, fromDate: birthday) if ( (dateComponentNow.month < dateComponentBirth.month) || ((dateComponentNow.month == dateComponentBirth.month) && (dateComponentNow.day < dateComponentBirth.day)) ) { return dateComponentNow.year - dateComponentBirth.year - 1 } else { return dateComponentNow.year - dateComponentBirth.year } }
To call the method and print out the return value in the console.
println("User Age: \(calculateAge(self.datePicker.date))")