遇到一个需求,需要把当前一周的日期展现出来,效果如图
Paste_Image.png#pragma mark 获取当前一周的时间
- (void)getCurrentWeek
{
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday
fromDate:now];
// 得到星期几
// 1(星期天) 2(星期二) 3(星期三) 4(星期四) 5(星期五) 6(星期六) 7(星期天)
NSInteger weekDay = [comp weekday];
// 得到几号
NSInteger day = [comp day];
NSLog(@"weekDay:%ld day:%ld",weekDay,day);
// 计算当前日期和这周的星期一和星期天差的天数
long firstDiff,lastDiff;
if (weekDay == 1) {
firstDiff = 1;
lastDiff = 0;
}else{
firstDiff = [calendar firstWeekday] - weekDay;
lastDiff = 7 - weekDay;
}
self.currentWeekArray = [[NSMutableArray alloc] init];
for (NSInteger i = firstDiff; i < lastDiff + 1; i ++) {
//从现在开始的24小时
NSTimeInterval secondsPerDay = i * 24*60*60;
NSDate *curDate = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];
NSString *dateStr = [dateFormatter stringFromDate:curDate];//几号
[self.currentWeekArray addObject:dateStr];
}
}
网友评论