我需要获得一年中所有星期的所有开始日期,我尝试过以下代码,但我不知道如何确切地知道每周的实际开始日期。
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *startDate = [NSDate date];
NSDateComponents *compStart = [cal components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit |NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit) fromDate:startDate];
[compStart setDay:1];
[compStart setMonth:1];
NSDate* weekstart=[cal dateFromComponents:compStart];
for(int i=0; i < 52; i++)
{
NSDateComponents* moveWeeks=[[NSDateComponents alloc] init];
moveWeeks.week=1;
weekstart=[cal dateByAddingComponents:moveWeeks toDate:weekstart options:0];
[arrayWeeks addObject:weekstart];
}
答案 0 :(得分:0)
此链接已回答了我的问题,我从0-51传递了weekOffset并完成了工作
代码需要稍加修改,所以这里修改后的代码对我来说是正确的
-(void)initArrayWeeks
{
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *startDate = [NSDate date];
NSDateComponents *compStart = [cal components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit |NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit) fromDate:startDate];
[compStart setDay:1];
[compStart setMonth:1];
NSDate* weekstart=[cal dateFromComponents:compStart];
for(int i = 0; i<51; i++)
{
NSArray *days = [self daysInWeek:i fromDate:weekstart];
[arrayWeeks addObject:days[0]];
}
}
-(NSArray*)daysInWeek:(int)weekOffset fromDate:(NSDate*)date
{
NSCalendar *calendar = [NSCalendar currentCalendar];
//ask for current week
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps=[calendar components:NSWeekCalendarUnit|NSYearCalendarUnit fromDate:date];
//create date on week start
NSDate* weekstart=[calendar dateFromComponents:comps];
if (weekOffset>0) {
NSDateComponents* moveWeeks=[[NSDateComponents alloc] init];
moveWeeks.week=weekOffset;
weekstart=[calendar dateByAddingComponents:moveWeeks toDate:weekstart options:0];
}
//add 7 days
NSMutableArray* week=[NSMutableArray arrayWithCapacity:7];
for (int i=1; i<=7; i++) {
NSDateComponents *compsToAdd = [[NSDateComponents alloc] init];
compsToAdd.day=i;
NSDate *nextDate = [calendar dateByAddingComponents:compsToAdd toDate:weekstart options:0];
[week addObject:nextDate];
}
return [NSArray arrayWithArray:week];
}