Calculate age from date of birth

I can not find the age from the date of birth. I got

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 } } 
+5
source share
4 answers

update: Xcode 8.2.1 • Swift 3.0.2

 extension Date { var age: Int { return Calendar.current.dateComponents([.year], from: self, to: Date()).year! } } let myDOB = Calendar.current.date(from: DateComponents(year: 1970, month: 9, day: 10))! let myAge = myDOB.age // 46 

Xcode 7.2 • Swift 2.1.1

You can use the components of the NSCalendar method to calculate the number of years from a specific date to today as follows:

 extension NSDate { var age: Int { return NSCalendar.currentCalendar().components(.Year, fromDate: self, toDate: NSDate(), options: []).year } } let myDOB = NSCalendar.currentCalendar().dateWithEra(1, year: 1970, month: 09, day: 10, hour: 0, minute: 0, second: 0, nanosecond: 0)! let myAge = myDOB.age // 46 
+21
source

Important:

The time zone must be set to create the UTC date of birth, otherwise there will be inconsistencies between time zones.

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

Using:

 let dob = Date(year: 1975, month: 1, day: 1) let age = dob.age print(age) 
+2
source

In Swift 2.0+, the computer age code should look something like this:

 extension NSDate { var age:Int { return NSCalendar.currentCalendar() .components(NSCalendarUnit.Year, fromDate: self, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0) .year } } 
0
source

Just use the DateTools module. Absolutely the easiest way. https://github.com/MatthewYork/DateTools

For Swift 3

 import DateTools let birthday: Date = .... let ageString = String((Date() as NSDate).years(from: birthday)) 
-1
source

Source: https://habr.com/ru/post/1214952/