I got a set of events that I'm displaying in a UITableView. Each event has a start date and and end date, with 1-3 days between them.
I'm trying to detect if a particular date range includes the start of a month (ex: August 1st), and add a special marker to that table view cell.
I've read that NSDate and calendar manipulations are expensive operations and my table view is already not the fastest in the world. How can I efficiently determine if a date range includes a start of a month?
Well, thinking pragmatically, you can check the months of each date:
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* startComp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:startDate];
NSDateComponents* endComp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:endDate];
if([startComp month] != [endComp month]){
// start of month included
}
You can do the same for the days, and if the endDate day value is LESS than the startDate day value then you know you have a 1st in there somewhere. Obviously this way will only work properly if the events span less than a month (which you said they do).
Check the month values of two end dates, if they are different you have a start of month otherwise you dont.
Edit: First check any endpoint(start or end) date day value equals 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With