取两个时间之间的所有时间集合
比如2021/12/01 14:01——2021/12/01 15:01
public class Test {
public static List<String> getDate(String startTime, String endTime){
//定义时间格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
List<String> list = new ArrayList<>();
try {
// 转化成日期类型
Date startDate = simpleDateFormat.parse(startTime);
Date endDate = simpleDateFormat.parse(endTime);
//用Calendar 进行日期比较判断
Calendar calendar = Calendar.getInstance();
while (startDate.getTime()<=endDate.getTime()){
// 把日期添加到集合
list.add(simpleDateFormat.format(startDate));
// 设置日期
calendar.setTime(startDate);
//把日期增加一分
calendar.add(Calendar.MINUTE, 1);
// 获取增加后的日期
startDate=calendar.getTime();
}
} catch (ParseException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
List<String> betweenDate = getDate("2021-12-01 14:01", "2021-12-02 15:01");
System.out.println(betweenDate);
}
}
如果是14:01——15:01之间的时间,修改SimpleDateFormat中的时间格式即可
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
时间间隔为分钟或者小时或者天数只需修改calendar.add(Calendar.MINUTE, 1)中的参数Date、HOUR即可