计算一年中所有周的第一天和最后一天
##准备
在看代码之前你可能需要先了解以下知识
* [NSDate、NSCalendar和NSDateComponents](https://www.jianshu.com/p/d0e56b09179a)
* [NSCalendar使用详解](https://blog.csdn.net/awaylin113/article/details/39557969)
##代码
```objc
- (void)weeksWithDateComponents:(NSDateComponents *)fromComp
toDateComponents:(NSDateComponents *)toComp{
//获取公历日历
NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
//一年中的天数或一年已过的天数
NSInteger daysOfYear = 0;
if (toComp) {//计算已过的天数
daysOfYear = [calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitYear forDate:[calendar dateFromComponents:toComp]];
}else{//计算一年的天数
//daysOfYear = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitYear forDate:[calendar dateFromComponents:fromComp]].length;
//在9.3系统里始终是31天
/*fixed 9.3 bug*/
for (NSInteger i = 1;
i <= 12;
i++) {
fromComp.month = i;
fromComp.day = 1;
NSDate *date = [calendar dateFromComponents:fromComp];
daysOfYear += [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
}
}
//月份移动至1月
fromComp.month = 1;
//记录当前第几周
NSInteger weekOfYear = 0;
//遍历每一天
for (NSInteger i = 1;
i <= daysOfYear;
i++) {
@autoreleasepool {
//移至当前天
fromComp.day = i;
NSDate *idate = [calendar dateFromComponents:fromComp];
NSDateComponents *comp = [calendar components:kCFCalendarUnitDay|kCFCalendarUnitWeekday|kCFCalendarUnitMonth fromDate:idate];
【计算一年中所有周的第一天和最后一天】//如果是周日或者一年的最后一天不是周日就将其计为一周
if ((i == daysOfYear&&comp.weekday != 1)||comp.weekday == 1) {//最后一天
weekOfYear += 1;
if (comp.weekday == 1) {
fromComp.day = MAX(i-6,1);
}else {
fromComp.day = i-(comp.weekday-2);
}
NSDate *fdate = [calendar dateFromComponents:fromComp];
NSString *reslut = [NSString stringWithFormat:@"第%zd周 (%zd月%zd日-%zd月%zd日)",weekOfYear,
[calendar ordinalityOfUnit:NSCalendarUnitMonth inUnit:NSCalendarUnitYear forDate:fdate],
[calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:fdate],
[calendar ordinalityOfUnit:NSCalendarUnitMonth inUnit:NSCalendarUnitYear forDate:idate],
[calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:idate]];
NSLog(@"%@",reslut);
}
}
}
}
```
##使用
```objc
NSDateComponents * fComp = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
fComp.month = 1;
fComp.day = 1;
NSDateComponents * tComp = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
[self weeksWithDateComponents:fComp toDateComponents:tComp];
```
推荐阅读
- 一个人的旅行,三亚
- 一个小故事,我的思考。
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量
- 开学第一天(下)
- 一个人的碎碎念
- 2018年11月19日|2018年11月19日 星期一 亲子日记第144篇
- 遇到一哭二闹三打滚的孩子,怎么办┃山伯教育
- 第326天
- Y房东的后半生14
- 奔向你的城市