开发者

How to calculate how many business days are between two dates?

A friend asked me yesterday if this was possible on the iPhone. I took a look at NSCalendar and all the related Classes but couldn't find a solution to this.

So I thought about this approach: If I had two dates dateA and dateB, I would have to make a for-loop and iterate over every single day in this interval. Then I would count the business days monday until friday, and return the result.

Then I went to bed, and I woke up with this probably much better idea: I need to know what day is it when I start. Lets say it's thursday. And then I must know how many days are in that interval. The last part is not hard to figure out. For the first part, I have no clue yet, but I believe there's an day of week value in NSCalendar. With that, I could do some simple math to calculate the am开发者_高级运维ount of business days.

Did anyone do that already on the iPhone?


How many times are you performing this calculation? Do the dates you'll be needing have to fall in a specific range?

If you're performing lots of these business date differences, consider building a lookup table that will store the number of business days between that date and some arbitrary date. Then to find the number of business days between two dates just subtract those lookup values. As for day of week calculations... remember that not all weekdays are "business days", so you'd need to somehow account for holidays.


Here are the pieces with which to do this calculation:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

// Determine the integer number of weeks between the two dates
NSDateComponents *components = [calendar components:NSWeekCalendarUnit fromDate:firstDate toDate:secondDate options:0];
NSInteger numWeeks = [components week];

// Determine the day of the week for each date
components = [calendar components:NSWeekdayCalendarUnit fromDate:firstDate];
NSInteger firstWeekday = [components weekday];
components = [calendar components:NSWeekdayCalendarUnit fromDate:secondDate];
NSInteger secondWeekday = [components weekday];

[calendar release];

I leave it as an exercise for the reader to do the necessary math to work out the number of business days from these values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜