How can I calculate the age of a person in year, month, days?

前端 未结 11 1208
谎友^
谎友^ 2020-11-27 05:52

I want to calculate the age of a person given the date of birth and the current date in years, months and days relative to the current date.

For example:

<         


        
11条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 06:27

    The Swift implementation of dreeves' answer.

    ps. instead of (y,m,d) (ynow,mnow,dnow) as the inputs, I use two NSDate's, which may be more handy in real world usages.

    extension NSDate {
    
        convenience init(ageDateString:String) {
            let dateStringFormatter = NSDateFormatter()
            dateStringFormatter.dateFormat = "yyyy-MM-dd"
            dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
            let d = dateStringFormatter.dateFromString(ageDateString)!
            self.init(timeInterval:0, sinceDate:d)
        }
    
        func ageFrom(date: NSDate) -> (Int, Int, Int) {
            let cal = NSCalendar.currentCalendar()
    
            let y = cal.component(NSCalendarUnit.Year, fromDate: date)
            let m = cal.component(NSCalendarUnit.Month, fromDate: date)
            let d = cal.component(NSCalendarUnit.Day, fromDate: date)
            let ynow = cal.component(NSCalendarUnit.Year, fromDate: self)
            let mnow = cal.component(NSCalendarUnit.Month, fromDate: self)
            let dnow = cal.component(NSCalendarUnit.Day, fromDate: self)
    
            let t0 = y * 12 + m - 1       // total months for birthdate.
            var t = ynow * 12 + mnow - 1;   // total months for Now.
            var dm = t - t0;              // delta months.
            if(dnow >= d) {
                return (Int(floor(Double(dm)/12)), dm % 12, dnow - d)
            }
            dm--
            t--
            return (Int(floor(Double(dm)/12)), dm % 12, Int((self.timeIntervalSince1970 - NSDate(ageDateString: "\(Int(floor(Double(t)/12)))-\(t%12 + 1)-\(d)").timeIntervalSince1970)/60/60/24))
        }
    
    }
    
    // sample usage
    let birthday = NSDate(ageDateString: "2012-7-8")
    print(NSDate().ageFrom(birthday))
    

提交回复
热议问题