1

我正在使用这种方法来获取当前周的第一天和最后几天:

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);

我想知道我应该改变什么来获得下周的第一天和最后一天以及从现在到两周的时间?

4

2 回答 2

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.

于 2013-03-09T18:36:43.670 回答
-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;

}

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

于 2013-03-09T18:37:42.060 回答