2013-03-09 120 views
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); 

,我想知道我应该在这个改变得到下一第一周和最后一天以及从现在起两周内?

+0

附注 - 不是每一个区域的一周开始于周日。许多国家星期一开始本周。你应该使用'NSCalendar firstWeekday'来获得正确的第一天。 – rmaddy 2013-03-09 18:27:44

+0

我应该怎么做?我需要更改我的代码? – MTA 2013-03-09 18:31:58

回答

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

+0

我需要改变NSDateComponents与你给的东西吗? – MTA 2013-03-09 18:47:54

+0

我显示的日期组件用于计算下一周。你有的是计算你需要的第一个日期。不要改变这些。 – rmaddy 2013-03-09 18:49:41

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

}

使用这个号码您添加或减去得到第一个或最后一周。你也可以通过简单的计算来获得下周的开始和结束日期。

+0

您正在回答错误的问题。 – rmaddy 2013-03-09 18:39:18

相关问题