java localdate 时间最大连续天数
public class DateUtils {
public static Date addDays(Date time, Integer day) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cd = Calendar.getInstance();
cd.setTime(time);
cd.add(Calendar.DATE, day);
return getDateByPattern(sdf.format(cd.getTime()), DAY_FORMAT);
} catch (Exception ex) {
log.error("日期增加自然天出错:{}", ex);
return null;
}
}
public static int continuousDayDate(List<Date> dateList) {
if (CollectionUtils.isEmpty(dateList) ) {
log.error("参数有误,连续天数为0 dayList{}" , dateList);
return 0;
}
List<LocalDate> datetimeList = dateList.stream()
.map(e-> LocalDateTime.ofInstant(e.toInstant(), ZoneId.systemDefault()))
.sorted(LocalDateTime::compareTo)
.map(LocalDateTime::toLocalDate)
.collect(Collectors.toList());
return continuousDayLocalDate(datetimeList);
}
public static int continuousDayLocalDate(List<LocalDate> dateList){
if (dateList == null || dateList.size() ==0) {
return 0;
}
dateList = dateList.stream().sorted(LocalDate::compareTo).collect(Collectors.toList());
int maxContinuousDay = 1;
int continuousDay = 1;
for (int i = 0; i < dateList.size(); i++) {
if (i == dateList.size() -1){
break;
}
LocalDate date = dateList.get(i);
LocalDate secondDate = dateList.get(i + 1);
if (date.plusDays(1).equals(secondDate)){
continuousDay ++;
if (continuousDay > maxContinuousDay){
maxContinuousDay = continuousDay;
}
}else {
continuousDay = 1;
}
}
return maxContinuousDay;
}
public static void main(String[] args) {
List<Date> dates = new ArrayList<>();
Date date = new Date();
dates.add(addDays(date, 1));
dates.add(addDays(date, 2));
dates.add(addDays(date, 5));
dates.add(addDays(date, 7));
dates.add(addDays(date, 8));
dates.add(addDays(date, 9));
System.out.println(continuousDayDate(dates));
List<LocalDate> list = new ArrayList<>();
list.add(LocalDate.now());
list.add(LocalDate.now().plusDays(1));
list.add(LocalDate.now().plusDays(2));
System.out.println(DateUtil.continuousDayLocalDate(list));
}
}
}
标签:dates,java,天数,addDays,dateList,add,date,return
From: https://www.cnblogs.com/bigorang/p/18059010