我有两个日期StartDate和EndDate。我想找一些具体的日子,例如这两个日期之间的星期一。
如何在两个日期之间执行循环?
答案 0 :(得分:10)
这个问题实际上有两个部分:
您可以使用NSCalendar
获取星期一。在下面的代码中,我使用当前日历并将一周的第一天更改为星期一,然后将日期设置为“一周的开始”。这是我从this answer获取的一个技巧。
NSDate *loopDate = // the start date you are looping from
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
currentCalendar.firstWeekday = 2; // Monday
[currentCalendar rangeOfUnit:NSWeekCalendarUnit startDate:&loopDate interval:NULL forDate:loopDate];
当我现在运行它(我的循环日期是3个月前)时,它会将Friday, May 17, 2013 at 5:57:26 PM GMT+2
更改为Monday, May 13, 2013 at 12:00:00 AM GMT+2
(这是之前的星期一)。
这很简单。创建“一周”的日期组件,并将其添加到日期,只要它小于结束日期。
NSDateComponents *oneWeek = [NSDateComponents new];
oneWeek.week = 1;
while ([loopDate compare:endDate] == NSOrderedAscending) {
loopDate = [currentCalendar dateByAddingComponents:oneWeek toDate:loopDate options:0];
// Do something with the date
}
当我运行此代码并记录我收到的日期时:
Monday, May 20, 2013 at 12:00:00 AM GMT+2
Monday, May 27, 2013 at 12:00:00 AM GMT+2
Monday, June 3, 2013 at 12:00:00 AM GMT+2
Monday, June 10, 2013 at 12:00:00 AM GMT+2
Monday, June 17, 2013 at 12:00:00 AM GMT+2
Monday, June 24, 2013 at 12:00:00 AM GMT+2
Monday, July 1, 2013 at 12:00:00 AM GMT+2
Monday, July 8, 2013 at 12:00:00 AM GMT+2
Monday, July 15, 2013 at 12:00:00 AM GMT+2
Monday, July 22, 2013 at 12:00:00 AM GMT+2
Monday, July 29, 2013 at 12:00:00 AM GMT+2
Monday, August 5, 2013 at 12:00:00 AM GMT+2
Monday, August 12, 2013 at 12:00:00 AM GMT+2
Monday, August 19, 2013 at 12:00:00 AM GMT+2
答案 1 :(得分:0)
使用NSCalendar
和NSDateComponents
将日期添加到日期。然后,您可以循环并重复添加句点,直到compare:
表示您已超过结束日期。