很常

iOS 获取指定日期的一周日期

2021-03-30  本文已影响0人  Ocean_e553

给出指定日期, 获取日期一周的日期(从周一到周日)

- (void)doTest {
    
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy/MM/dd";
    nowDate = [formatter dateFromString:@"2020/03/18"]; //
    
    NSArray *dates = [self currentWeekDaiesForDate:nowDate];
    
    formatter.weekdaySymbols = @[@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", ];
    for (NSDate *date in dates) {
        formatter.dateFormat = @"MM/dd";
        NSString *dateInfo = [formatter stringFromDate:date];
        formatter.dateFormat = @"EEEE";
        NSString *weekInfo = [formatter stringFromDate:date];
        NSLog(@"%@ --> %@", dateInfo, weekInfo);
    }
}

- (NSArray *)currentWeekDaiesForDate:(NSDate *)nowDate {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *nowComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday  fromDate:nowDate];
    // 获取今天是周几
    NSInteger weekDay = [nowComp weekday];
    // 获取今天是几号
    NSInteger day = [nowComp day];
     // 计算当前日期和本周的星期一相差天数
    //天/一/二/三/四/五/六
    //1 /2 /3  /4 /5 /6 / 7
    NSInteger detal;
    if (weekDay == 1) {
        detal = -6;
    } else {
        detal = -(weekDay-2);
    }
    
    //获取周一日期
    NSDateComponents *baseDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:nowDate];
    [baseDayComp setDay:day + detal];
    NSDate *mondayDate = [calendar dateFromComponents:baseDayComp];
    NSMutableArray *results = [[NSMutableArray alloc] init];
    //计算从周一开始的七天日期
    for (int i = 0; i < 7; i ++) {
        //从现在开始的24小时
        NSTimeInterval secondsPerDay = i * 24*60*60;
        NSDate *curDate = [NSDate dateWithTimeInterval:secondsPerDay sinceDate:mondayDate];
        
        // 时区转换
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSInteger interval = [zone secondsFromGMTForDate:curDate];
        NSDate *localeDate = [curDate  dateByAddingTimeInterval: interval];
        [results addObject:localeDate];
    }
    return results;
}
上一篇下一篇

猜你喜欢

热点阅读