获取一周的第一天和最后一天

时间:2013-03-09 18:12:29

标签: iphone ios objective-c

我正在使用此方法获取当前周和前几天:

NSDate *weekDate = [NSDate date];
NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *currentComps = [myCalendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekOfYearCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:weekDate];
int ff = currentComps.weekOfYear;
NSLog(@"1  %d", ff);

[currentComps setWeekday:1]; // 1: sunday
NSDate *firstDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
[currentComps setWeekday:7]; // 7: saturday
NSDate *lastDayOfTheWeek = [myCalendar dateFromComponents:currentComps];

NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
myDateFormatter.dateFormat = @"dd/MM/yyyy";
NSString *firstStr = [myDateFormatter stringFromDate:firstDayOfTheWeek];
NSString *secondStr = [myDateFormatter stringFromDate:lastDayOfTheWeek];

NSLog(@"first - %@ \nlast - %@", firstStr, secondStr);

而且我想知道我应该在这个方面做些什么改变来获得下一周的第一天和最后一天以及从现在开始的两周?

2 个答案:

答案 0 :(得分:4)

要获得下周,请将{7}添加至firstDayOfTheWeek,然后添加lastDayOfTheWeek

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:7];
NSDate *firstDayOfNextWeek = [myCalendar dateByAddingComponents:comps toDate:firstDayOfTheWeek options:0];

此代码假定为期7天。理想情况下,您可以使用获得一周实际长度的代码替换此假设。

旁注:您的代码假设星期日开始。许多语言环境在周一等其他日子开始。变化:

[currentComps setWeekday:1];

为:

[currentComps setWeekday:[myCalendar firstWeekday]];

然后我会更改lastDayOfTheWeek的计算,只需将{6}添加到firstDayOfWeek

答案 1 :(得分:-1)

使用下面的代码返回当前当前每周天数的索引。例如,如果它今天是星期六,那么它会给你7个星期的最后一天。

-(int)currentdayweeklynumber{

NSDate *CurrentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];// you can use your format.

//Week Start Date 
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:CurrentDate];
int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:CurrentDate] weekday];
NSLog(@" dayofweek=%d",dayofweek);
return dayofweek;

}

使用此数字,您可以添加或减去第一周或最后一周。您也可以通过简单的计算使用此获取下周的开始和结束日期。