Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If all you care about is tomorrow or yesterday vs. a specific date, then you can save yourself a lot of work and just test whether the dates are only one calendar day apart.</p> <p>To do that, compare the dates to find which is earlier and which is later (and if they compare equal, bail out with that result), then test whether 1 day after the earlier date produces a date with the same year, month, and day-of-month as the later date.</p> <hr> <p>If you really do want to know exactly how many calendar days there are from one date to the other:</p> <ol> <li>Send the calendar a <code>components:fromDate:</code> message to get the year, month, and day-of-the-month of the first date.</li> <li>Same as #1, but for the second date.</li> <li>If the two dates are in the same year and month, subtract one day-of-month from the other and pass to <code>abs</code> (see <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/abs.3.html" rel="nofollow noreferrer">abs(3)</a>) to take the absolute value.</li> <li><p>If they are not in the same year and month, test whether they are in adjacent months (e.g., December 2010 to January 2011, or June 2010 to July 2010). If they are, add the number of days in the earlier date's month (which you can obtain by sending the calendar a <code>rangeOfUnit:inUnit:forDate:</code> message, passing <code>NSDayCalendarUnit</code> and <code>NSMonthCalendarUnit</code>, respectively) to the day-of-month of the later date, then compare that result to the earlier date's day-of-month.</p> <p>For example, when comparing 2010-12-31 to 2011-01-01, you would first determine that these are in adjacent months, then add 31 (number of days in 2010-12) to 1 (day-of-month of 2011-01-01), then subtract 31 (day-of-month of 2010-12-31) from that sum. Since the difference is 1, the earlier date is one day before the later date.</p> <p>When comparing 2010-12-<em>30</em> to 2011-01-<em>02</em>, you would determine that they are in adjacent months, then add 31 (days in 2010-12) to 2 (day-of-month of 2011-01-02), then subtract 30 (day-of-month of 2010-12-30) from that sum. 33 minus 30 is 3, so these dates are three calendar days apart.</p></li> </ol> <hr> <p>Either way, I strongly suggest writing unit tests at least for this code. I've found that date-handling code is among the most likely to have subtle bugs that only manifest, say, twice a year.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload