Get the exact difference between 2 dates for a single NSDateComponent

前端 未结 4 1650
暗喜
暗喜 2021-01-20 10:49

How can I get the exact difference (in decimal) between 2 values of NSDate.

Eg. Jan 15 2016 to Jul 15 2017 = <

4条回答
  •  抹茶落季
    2021-01-20 11:26

    According to NASA, there are 365.2422 days per year on average. Here, I round that up to 365.25 days per year:

    let components = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: fromDate, toDate: toDate, options: [])
    
    var totalYears = Double(components.year)
    totalYears += Double(components.month) / 12.0
    totalYears += Double(components.day) / 365.25
    

    Obviously, this depends on your assumptions. If you want to count of leap days between fromDate and toDate, it will be more complicated.

    Some sample outputs:

    From date      To date        Total Years
    ------------   ------------   ------------
    Jan 15, 2016   Jul 15, 2017   1.5
    Jan 15, 2016   Apr 14, 2016   0.25
    Jan 15, 2016   Aug 15, 2017   1.5833
    Jan 15, 2016   Jan 14, 2018   1.9988
    

提交回复
热议问题