Alex Stone
Alex Stone

Reputation: 47358

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?

Upvotes: 3

Views: 1436

Answers (3)

Alessandro Vendruscolo
Alessandro Vendruscolo

Reputation: 14875

You could check if the end date is lower than the start date.

E.g.: start = Jun 30, end = Jul 2.

NSDate * start, end;

NSInteger startDay = [[start descriptionWithCalendarFormat:@"%d" timeZone:nil locale:nil] intValue];
NSInteger endDay = [[start descriptionWithCalendarFormat:@"%d" timeZone:nil locale:nil] intValue];

if (endDay < startDay) {
    // bingo!
}

Upvotes: 3

rad
rad

Reputation: 1126

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.

Upvotes: 3

Thomas Clayson
Thomas Clayson

Reputation: 29925

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

Upvotes: 3

Related Questions