Calculate age from birth date using NSDateComponents in Swift
Solution 1:
You get an error message because 0
is not a valid value for NSCalendarOptions
.
For "no options", use NSCalendarOptions(0)
or simply nil
:
let ageComponents = calendar.components(.CalendarUnitYear,
fromDate: birthday,
toDate: now,
options: nil)
let age = ageComponents.year
(Specifying nil
is possible because NSCalendarOptions
conforms to the RawOptionSetType
protocol which in turn inherits
from NilLiteralConvertible
.)
Update for Swift 2:
let ageComponents = calendar.components(.Year,
fromDate: birthday,
toDate: now,
options: [])
Update for Swift 3:
Assuming that the Swift 3 types Date
and Calendar
are used:
let now = Date()
let birthday: Date = ...
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
let age = ageComponents.year!
Solution 2:
I create this method its very easy just put the birthday date in the method and this will return the Age as a Int
Swift 3
func calcAge(birthday: String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let now = Date()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: [])
let age = calcAge.year
return age!
}
Swift 2
func calcAge(birthday: String) -> Int{
let dateFormater = NSDateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.dateFromString(birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()
let calcAge = calendar.components(.Year, fromDate: birthdayDate!, toDate: now, options: [])
let age = calcAge.year
return age
}
Usage
print(calcAge("06/29/1988"))
Solution 3:
For swift 4 works fine
func getAgeFromDOF(date: String) -> (Int,Int,Int) {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "YYYY-MM-dd"
let dateOfBirth = dateFormater.date(from: date)
let calender = Calendar.current
let dateComponent = calender.dateComponents([.year, .month, .day], from:
dateOfBirth!, to: Date())
return (dateComponent.year!, dateComponent.month!, dateComponent.day!)
}
let age = getAgeFromDOF(date: "2000-12-01")
print("\(age.0) Year, \(age.1) Month, \(age.2) Day")
Solution 4:
This works for Swift 3
let myDOB = Calendar.current.date(from: DateComponents(year: 1994, month: 9, day: 10))!
let myAge = Calendar.current.dateComponents([.month], from: myDOB, to: Date()).month!
let years = myAge / 12
let months = myAge % 12
print("Age : \(years).\(months)")
Solution 5:
This is working in swift 3 for me..
let now = NSDate()
let calendar : NSCalendar = NSCalendar.current as NSCalendar
let ageComponents = calendar.components(.year, from: datePickerView.date, to: now as Date, options: [])
let age = ageComponents.year!
ageCalculated.text = String(age)
Thanks to @Martin R