Created
May 23, 2017 05:46
-
-
Save andatta/3b2010604aa4bd553bf0098470f6dbb8 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 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
func calculateAge(dob : String) -> (year :Int, month : Int, day : Int){ | |
let df = NSDateFormatter() | |
df.dateFormat = "yyyy-MM-dd" | |
let date = df.dateFromString(dob) | |
guard let val = date else{ | |
return (0, 0, 0) | |
} | |
var years = 0 | |
var months = 0 | |
var days = 0 | |
let cal = NSCalendar.currentCalendar() | |
years = cal.component(.Year, fromDate: NSDate()) - cal.component(.Year, fromDate: val) | |
let currMonth = cal.component(.Month, fromDate: NSDate()) | |
let birthMonth = cal.component(.Month, fromDate: 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, fromDate: NSDate()) < cal.component(.Day, fromDate: val){ | |
months = months - 1 | |
} | |
} else if months == 0 && cal.component(.Day, fromDate: NSDate()) < cal.component(.Day, fromDate: val) | |
{ | |
years = years - 1 | |
months = 11 | |
} | |
//Calculate the days | |
if cal.component(.Day, fromDate: NSDate()) > cal.component(.Day, fromDate: val){ | |
days = cal.component(.Day, fromDate: NSDate()) - cal.component(.Day, fromDate: val) | |
} | |
else if cal.component(.Day, fromDate: NSDate()) < cal.component(.Day, fromDate: val) | |
{ | |
let today = cal.component(.Day, fromDate: NSDate()) | |
let date = cal.dateByAddingUnit(.Month, value: -1, toDate: NSDate(), options: []) | |
days = (cal.component(.Day, fromDate: date!) - cal.component(.Day, fromDate: 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
Thankyou!
this is the Swift 4 version. plus that fix from @helenhell