iOS

计算一年中所有周的第一天和最后一天

准备

在看代码之前你可能需要先了解以下知识

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

- (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 (comp.weekday == 2) {
weekOfYear += 1;
fromComp.day = MIN(i+6,daysOfYear);
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);
}
}
}
}

使用

1
2
3
4
5
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];