Get the exact difference between 2 dates for a single NSDateComponent

前端 未结 4 1652
暗喜
暗喜 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:22

    There isn't a perfect answer to this question. Different years are slightly different lengths. You have to make some assumptions.

    If you assume 365.2425 days per year, with each day having 24 hours, then the calculation is trivial:

    let secondsPerYear: NSTimeInterval = NSTimeInterval(365.2425 * 24 * 60 * 60)
    let secondsBetweenDates = 
      date2.timeIntervalSinceReferenceDate - date1.timeIntervalSinceReferenceDate;
    let yearsBetweenDates = secondsBetweenDates / secondPerYear
    

    But there are lots of edge cases and weirdness to deal with. Because of leap years, some years have 365 days, and some have 366. Then there's leap seconds.

    If you get rid of months in @CodeDifferent's answer then you'll get an answer that allows for leap days between the dates.

    But, as Code Different pointed out, his answer as written actually gives answers that seem more accurate, even though they are not. (A difference of 3 months will always yield .25 years, and will ignore longer/shorter months. Is that the right thing to do? Depends on your goal and your assumptions.)

提交回复
热议问题