How to calculate how many Sundays are between two dates?
I've already got this data, which was pretty simple:
NSInteger numWeeks = ...;
NSInteger weekdayOfDateA = ...; // i.e. 1 for Sunday
NSInteger weekdayOfDateB = ...; // i.e. 6 for Friday
Just from the logical point of view, I could safely assume that every week in numWeeks has got one Sunday, right?
So numWeeks represents already my number of Sundays. Almost.
But how would I handle the edge cases? i.e. if dateA starts on a Wednesday, and dateB ends on a Monday, that must not 开发者_如何学Cneccessarily be a complete set of weeks. It may be like 10 and a half week or something. The problem is: Which part of the interval can be safely ignored since it's "sucked in" already by numWeeks?
I guess NSCalendar & Co. start looking at the first date and simply count up 7 days for each week. So is the only thing I must care of the last tail of that interval?
Think of your weeks as starting e.g. on Monday and ending on Sunday. Determine the number of these weeks you have - you'll have one Sunday for each - in determining this (which you'll probably want to do by rolling e.g. the start forward to the first Monday), if you pass by a Sunday add 1 to the result.
精彩评论