Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's an implementation I used to determine the number of calendar days between two dates:</p> <pre><code>+ (NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime { NSDate *fromDate; NSDate *toDate; NSCalendar *calendar = [NSCalendar currentCalendar]; [calendar rangeOfUnit:NSCalendarUnitDay startDate:&amp;fromDate interval:NULL forDate:fromDateTime]; [calendar rangeOfUnit:NSCalendarUnitDay startDate:&amp;toDate interval:NULL forDate:toDateTime]; NSDateComponents *difference = [calendar components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0]; return [difference day]; } </code></pre> <p><strong>EDIT:</strong></p> <p>Fantastic solution above, here's Swift version below as an extension on <code>NSDate</code>:</p> <pre><code>extension NSDate { func numberOfDaysUntilDateTime(toDateTime: NSDate, inTimeZone timeZone: NSTimeZone? = nil) -&gt; Int { let calendar = NSCalendar.currentCalendar() if let timeZone = timeZone { calendar.timeZone = timeZone } var fromDate: NSDate?, toDate: NSDate? calendar.rangeOfUnit(.Day, startDate: &amp;fromDate, interval: nil, forDate: self) calendar.rangeOfUnit(.Day, startDate: &amp;toDate, interval: nil, forDate: toDateTime) let difference = calendar.components(.Day, fromDate: fromDate!, toDate: toDate!, options: []) return difference.day } } </code></pre> <p>A bit of force unwrapping going on which you may want to remove depending on your use case.</p> <p>The above solution also works for time zones other than the current time zone, perfect for an app that shows information about places all around the world.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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