Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate age from birth date

Tags:

ios

swift

I cant find age in from birth date. What I got is

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) 

My code

override func viewDidLoad() {
        super.viewDidLoad()
var dateString = user.birthday
        var dateFormatter = NSDateFormatter()
        // this is imporant - we set our input date format to match our input string
        dateFormatter.dateFormat = "dd-MM-yyyy"
        // voila!
        var dateFromString = dateFormatter.dateFromString(dateString)

        let age = calculateAge(dateFromString!)
}

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())
        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
        }
    }
like image 888
Nurdin Avatar asked Mar 09 '15 05:03

Nurdin


People also ask

How did you calculated my age?

The method of calculating age involves the comparison of a person's date of birth with the date on which the age needs to be calculated. The date of birth is subtracted from the given date, which gives the age of the person. Age = Given date - Date of birth.

How can I find my birth date online?

How to Calculate date of Birth | Birthday. To do this manually, you would need to know your exact current age and the date of the day when you're calculating it from. Then you can simple subtract the number of years from the current year, number of days and you will have found out your date of birth.


2 Answers

update: Xcode 11 • Swift 5.1

You can use the Calendar method dateComponents to calculate how many years from a specific date to today:

extension Date {
    var age: Int { Calendar.current.dateComponents([.year], from: self, to: Date()).year! }
}

let dob = DateComponents(calendar: .current, year: 2000, month: 6, day: 30).date!
let age = dob.age // 19

enter image description here

like image 149
Leo Dabus Avatar answered Sep 17 '22 14:09

Leo Dabus


Important:

The timezone must be set to create a UTC birth date otherwise there will be inconsistencies between timezones.

Swift 3

extension Date {

    //An integer representation of age from the date object (read-only).
    var age: Int {
        get {
            let now = Date()
            let calendar = Calendar.current

            let ageComponents = calendar.dateComponents([.year], from: self, to: now)
            let age = ageComponents.year!
            return age
        }
    }

    init(year: Int, month: Int, day: Int) {
        var dc = DateComponents()
        dc.year = year
        dc.month = month
        dc.day = day

        var calendar = Calendar(identifier: .gregorian)
        calendar.timeZone = TimeZone(secondsFromGMT: 0)!
        if let date = calendar.date(from: dc) {
            self.init(timeInterval: 0, since: date)
        } else {
            fatalError("Date component values were invalid.")
        }
    }

}

Usage:

let dob = Date(year: 1975, month: 1, day: 1)
let age = dob.age

print(age)
like image 33
George Filippakos Avatar answered Sep 20 '22 14:09

George Filippakos