Calculate age from birth date

前端 未结 4 734
北荒
北荒 2020-12-09 06:34

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

4条回答
  •  甜味超标
    2020-12-09 07:15

    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
    

提交回复
热议问题