iOS 获取一段时间内的所有日期(打印出每一天)
2020-12-10 本文已影响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;
}