How to calculate the age based on NSDate

后端 未结 11 1969
孤街浪徒
孤街浪徒 2020-12-04 09:07

how to calculate the age based on the birth date in this format 6/24/1976 mon/date/year...

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 09:42

    A simple to use swift extension to get the age/how old is a NSDate

    extension NSDate {
        var age: Int {
            let calendar: NSCalendar = NSCalendar.currentCalendar()
            let now = calendar.startOfDayForDate(NSDate())
            let birthdate = calendar.startOfDayForDate(self)
            let components = calendar.components(.Year, fromDate: birthdate, toDate: now, options: [])
            return components.year
        }
    }
    

    Exemple:

    NSDate(timeIntervalSince1970:0).age // => 45 (as of nov 2015) Epoch happened 45 year ago !
    

    By the way, you should be careful, this is the western conception of age, the counting is different in some other countries (Korea for exemple).

提交回复
热议问题