获取本周的所有日期(从周一到周日)

// 获取当前一周的日期
- (NSArray *)getWeekTime
{
    NSMutableArray *weekArray = [NSMutableArray arrayWithCapacity:7];
    
    NSDate *nowDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit fromDate:nowDate];
    // 获取今天是周几
    // 1(星期天) 2(星期一) 3(星期二) 4(星期三) 5(星期四) 6(星期五) 7(星期六)
    NSInteger weekDay = [comp weekday];
    
    // 获取几天是几号
    NSInteger day = [comp day];
    
    if (weekDay == 1)
    {
        for (int i = 7; i >=1; i --)
        {
            // 在当前日期(去掉时分秒)基础上加上差的天数
            NSDateComponents *weekComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit  fromDate:nowDate];
            
            //由于weekDay是一周的最后一天,所以减去7得到周一
            [weekComp setDay:day + (weekDay - i)];
            NSDate *dayOfWeek = [calendar dateFromComponents:weekComp];
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"MM.dd"];
            
            NSString *dayString = [formatter stringFromDate:dayOfWeek];
            [weekArray addObject:dayString];
        }
    }
    else
    {
        for (int i = 2; i <= 8; i ++)
        {
            NSDateComponents *weekComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit  fromDate:nowDate];
            [weekComp setDay:day + (i - weekDay)];
            NSDate *dayOfWeek = [calendar dateFromComponents:weekComp];
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"MM.dd"];
            
            NSString *dayString = [formatter stringFromDate:dayOfWeek];
            [weekArray addObject:dayString];
        }
    }
    return weekArray;
}

你可能感兴趣的:(获取本周的所有日期(从周一到周日))