Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone iOS NSDate how to detect if a date range includes a start of a month?

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?

like image 834
Alex Stone Avatar asked Dec 10 '25 13:12

Alex Stone


2 Answers

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).

like image 109
Thomas Clayson Avatar answered Dec 13 '25 01:12

Thomas Clayson


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.

like image 44
rad Avatar answered Dec 13 '25 03:12

rad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!