Calculate age from birth date using NSDateComponents in Swift

梦想的初衷 提交于 2019-11-27 01:32:48

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!
Gal Mesika

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"))

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")

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)")

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

This is the best way on swift 5

lazy var dateFormatter : DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        formatter.locale = Locale(identifier: "en_US_POSIX")
        return formatter
    }()

let birthday = dateFormatter.date(from: "1980-04-25")
let timeInterval = birthday?.timeIntervalSinceNow
let age = abs(Int(timeInterval! / 31556926.0))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!