Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you have a lot of these date comparisons, then the calls to <code>calendar:components:fromDate</code> start to take up a lot of time. According to some profiling I have done, they seem to be quite expensive.</p> <p>Say you are trying to determine which from some array of dates, say <code>NSArray *datesToCompare</code>, are the same day as some given day, say <code>NSDate *baseDate</code>, then you can use something like the following (partly adapted from an answer above):</p> <pre><code>NSDate *baseDate = [NSDate date]; NSArray *datesToCompare = [NSArray arrayWithObjects:[NSDate date], [NSDate dateWithTimeIntervalSinceNow:100], [NSDate dateWithTimeIntervalSinceNow:1000], [NSDate dateWithTimeIntervalSinceNow:-10000], [NSDate dateWithTimeIntervalSinceNow:100000], [NSDate dateWithTimeIntervalSinceNow:1000000], [NSDate dateWithTimeIntervalSinceNow:50], nil]; // determine the NSDate for midnight of the base date: NSCalendar* calendar = [NSCalendar currentCalendar]; NSDateComponents* comps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:baseDate]; NSDate* theMidnightHour = [calendar dateFromComponents:comps]; // set up a localized date formatter so we can see the answers are right! NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; [dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; // determine which dates in an array are on the same day as the base date: for (NSDate *date in datesToCompare) { NSTimeInterval interval = [date timeIntervalSinceDate:theMidnightHour]; if (interval &gt;= 0 &amp;&amp; interval &lt; 60*60*24) { NSLog(@"%@ is on the same day as %@", [dateFormatter stringFromDate:date], [dateFormatter stringFromDate:baseDate]); } else { NSLog(@"%@ is NOT on the same day as %@", [dateFormatter stringFromDate:date], [dateFormatter stringFromDate:baseDate]); } } </code></pre> <p>Output:</p> <pre><code>Nov 23, 2011 1:32:00 PM is on the same day as Nov 23, 2011 1:32:00 PM Nov 23, 2011 1:33:40 PM is on the same day as Nov 23, 2011 1:32:00 PM Nov 23, 2011 1:48:40 PM is on the same day as Nov 23, 2011 1:32:00 PM Nov 23, 2011 10:45:20 AM is on the same day as Nov 23, 2011 1:32:00 PM Nov 24, 2011 5:18:40 PM is NOT on the same day as Nov 23, 2011 1:32:00 PM Dec 5, 2011 3:18:40 AM is NOT on the same day as Nov 23, 2011 1:32:00 PM Nov 23, 2011 1:32:50 PM is on the same day as Nov 23, 2011 1:32:00 PM </code></pre>
 

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