Calculate age from birth date

前端 未结 4 719
北荒
北荒 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:06

    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)
    

提交回复
热议问题