准备
在看代码之前你可能需要先了解以下知识
代码
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{
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; } } 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];
|