繁体   English   中英

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

[英]Get the first day and last day of a week

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

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

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

要获得下一周,请在firstDayOfTheWeeklastDayOfTheWeek添加7天。

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的计算,只需在firstDayOfWeek添加6天。

使用下面的代码返回当前当前每周天数的索引。 例如,如果它今天是星期六,那么它会给你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;

}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM