美文网首页很常
iOS 获取一段时间内的所有日期(打印出每一天)

iOS 获取一段时间内的所有日期(打印出每一天)

作者: 不要虚度美好的时光 | 来源:发表于2020-12-10 11:22 被阅读0次

    提前一天:

    NSArray *dataArr = [CommonTool getDatesWithStartDate:@"2020-12-05" endDate:@"2020-12-10"];
    
    // iOS获取两个日期之间的所有日期数组,精确到天
    + (NSArray*)getDatesWithStartDate:(NSString *)startDate endDate:(NSString *)endDate {
        
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
        
        //字符串转时间
        NSDateFormatter *matter = [[NSDateFormatter alloc] init];
        matter.dateFormat = @"yyyy-MM-dd";
        NSDate *start = [matter dateFromString:startDate];
        NSDate *end = [matter dateFromString:endDate];
        
        NSMutableArray *componentAarray = [NSMutableArray array];
        NSComparisonResult result = [start compare:end];
        NSDateComponents *comps;
        while (result != NSOrderedDescending) {
            comps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |  NSCalendarUnitWeekday fromDate:start];
            [componentAarray addObject:start];
            
            //后一天
            [comps setDay:([comps day]+1)];
            start = [calendar dateFromComponents:comps];
            
            //对比日期大小
            result = [start compare:end];
        }
        return componentAarray;
    }
    

    相关文章

      网友评论

        本文标题:iOS 获取一段时间内的所有日期(打印出每一天)

        本文链接:https://www.haomeiwen.com/subject/gqblgktx.html