-
-
Save saud978/67d3d4122a299ae7bc1cc6d8b61b2502 to your computer and use it in GitHub Desktop.
Swift code to calculate age in years, months and days from a person's dob
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Updated to swift 4.2 | |
func calculateAge(dob : String) -> (Int, Int, Int){ | |
let df = DateFormatter() | |
df.dateFormat = "yyyy-MM-dd" | |
let date = df.date(from: dob) | |
guard let val = date else { | |
return (0, 0, 0) | |
} | |
var years = 0 | |
var months = 0 | |
var days = 0 | |
let cal = NSCalendar.current | |
years = cal.component(.year, from: NSDate() as Date) - cal.component(.year, from: val) | |
let currMonth = cal.component(.month, from: NSDate() as Date) | |
let birthMonth = cal.component(.month, from: val) | |
//get difference between current month and birthMonth | |
months = currMonth - birthMonth | |
//if month difference is in negative then reduce years by one and calculate the number of months. | |
if months < 0 | |
{ | |
years = years - 1 | |
months = 12 - birthMonth + currMonth | |
if cal.component(.day, from: NSDate() as Date) < cal.component(.day, from: val){ | |
months = months - 1 | |
} | |
} else if months == 0 && cal.component(.day, from: NSDate() as Date) < cal.component(.day, from: val) | |
{ | |
years = years - 1 | |
months = 11 | |
} | |
//Calculate the days | |
if cal.component(.day, from: NSDate() as Date) > cal.component(.day, from: val){ | |
days = cal.component(.day, from: NSDate() as Date) - cal.component(.day, from: val) | |
} | |
else if cal.component(.day, from: NSDate() as Date) < cal.component(.day, from: val) | |
{ | |
let today = cal.component(.day, from: NSDate() as Date) | |
let date = cal.date(byAdding: .month, value: -1, to: NSDate() as Date) | |
days = (cal.component(.day, from: date!) - cal.component(.day, from: val)) + today | |
} else | |
{ | |
days = 0 | |
if months == 12 | |
{ | |
years = years + 1 | |
months = 0 | |
} | |
} | |
return (years, months, days) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment