从出生date计算年龄

从出生那天起,我无法find年龄。 我得到的是

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

我的代码

 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 } } 

更新: 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

您可以使用NSCalendar方法组件来计算从特定date到今天多less年,如下所示:

 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 

重要:

时区必须设置为创buildUTC出生date,否则时区之间将存在不一致。

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

用法:

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

在Swift 2.0+年代,计算代码应该是这样的:

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

只需使用DateTools窗格即可。 绝对是最简单的方法。 https://github.com/MatthewYork/DateTools

对于Swift 3

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