如何将
{2022-08-01,2022-08-02,2022-08-03,2022-08-04,2022-08-06,2022-08-07}
这种时间点的list转化为
{"startDate": "2022-08-01","endDate": "2022-08-04"},
{"startDate": "2022-08-06","endDate": "2022-08-07"}
这种时间区间list呢?
先说思路:
1、先对时间点按时间顺序排序。
2、在进⾏循环⽐较的时候,下一个时间点跟上一个时间点如果相差大于1天,证明不连续了,记录当前时间点跟下一个时间点
代码如下:
public class DateUtil implements Comparator {
/**
* 合并时间点为时间段
* @param timePoint 时间点
* @return 时间段list
*/
public static List<Map<String, String>> mergeDatePoint(List<Date> timePoint) {
Collections.sort(timePoint,new DateUtil());
List<Map<String, String>> result = new ArrayList<Map<String, String>>();
Map<String, String> map = new HashMap<String, String>();
map.put("startDate", DateUtil.convertDateToString(timePoint.get(0), "yyyy-MM-dd"));
if (timePoint.size() == 1) {
map.put("endDate", DateUtil.convertDateToString(timePoint.get(0), "yyyy-MM-dd"));
result.add(map);
return result;
}
for(int i = 1; i < timePoint.size(); i ++) {
if (daysBetween(timePoint.get(i - 1), timePoint.get(i)) != 1) {
map.put("endDate", DateUtil.convertDateToString(timePoint.get(i - 1), "yyyy-MM-dd"));
result.add(map);
map = new HashMap<String, String>();
map.put("startDate", DateUtil.convertDateToString(timePoint.get(i), "yyyy-MM-dd"));
}
if (i == timePoint.size() - 1) {
map.put("endDate", DateUtil.convertDateToString(timePoint.get(i), "yyyy-MM-dd"));
result.add(map);
}
}
return result;
}
//获取相差天数
private static int daysBetween(Date sendDate, Date startDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
sendDate = sdf.parse(sdf.format(sendDate));
startDate = sdf.parse(sdf.format(startDate));
} catch (Exception e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(sendDate);
long time1 = cal.getTimeInMillis();
cal.setTime(startDate);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
}
@Override
public int compare(Object o1, Object o2) {
Date date1 = (Date) o1;
Date date2 = (Date) o2;
return date1.compareTo(date2);
}
}
实测数据如下:
有四段不连续的时间段
结果图如下:
按照连续的时间区间分成4个对象
注意的是:
1.一定要先对时间点排序才能实现
2.本篇内容不支持出现时分秒的日期划分
3.传入的是时间点而非时间区间,暂不支持合并,需要合并的时间区间的请移步别的博客