导入hutool依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.1.2</version>
</dependency>
/**
* 获取时间间隔(分钟)hutool的DateUtil
* @return
*/
public static int getBetweenMinute(Date date){
// DateUtil.beginOfDay(new Date())当天时间凌晨
//当前时间 目标时间 时间间隔类型(时、分、秒。。。)
long between = DateUtil.between(DateUtil.date(), date, DateUnit.MINUTE);
return Math.toIntExact(between);
}
/**
* 生成相隔时间的数组
*/
public static List<String> minuteList(){
Date date = new Date();
List<Date> ds = test(date);
List<String> list = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (Date d : ds) {
list.add(sdf.format(d));
}
return list;
}
public static void main(String[] args) {
// Date date = new Date();
// List<Date> ds = test(date);
//
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// for (Date d : ds) {
// System.out.println(sdf.format(d));
// }
System.out.println(minuteList());
}
public static List<String> findDates(String stime, String etime)
throws ParseException {
List<String> allDate = new ArrayList();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dBegin = sdf.parse(stime);
Date dEnd = sdf.parse(etime);
allDate.add(sdf.format(dBegin));
Calendar calBegin = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calEnd.setTime(dEnd);
// 测试此日期是否在指定日期之后
while (dEnd.after(calBegin.getTime())) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
calBegin.add(Calendar.DAY_OF_MONTH, 1);
allDate.add(sdf.format(calBegin.getTime()));
}
return allDate;
}
static List<Date> test(Date date) {
Date start = dayStartDate(date);//转换为天的起始date
Date nextDayDate = nextDay(start);//下一天的date
List<Date> result = new ArrayList<Date>();
while (start.compareTo(nextDayDate) < 0) {
result.add(start);
//日期加5分钟
start = addFiveMin(start, 15);
}
return result;
}
private static Date addFiveMin(Date start, int offset) {
Calendar c = Calendar.getInstance();
c.setTime(start);
c.add(Calendar.MINUTE, offset);
return c.getTime();
}
private static Date nextDay(Date start) {
Calendar c = Calendar.getInstance();
c.setTime(start);
c.add(Calendar.DATE, 1);
return c.getTime();
}
private static Date dayStartDate(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
}
/**
* @author wuqs
* @version 1.0.0
* @Description 获取i分钟后的时间
* @createTime 2021年11月29日 15:58:00
*/
public static String getMinute(int i) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Calendar nowTime2 = Calendar.getInstance();
nowTime2.add(Calendar.MINUTE, i * 15);
return sdf.format(nowTime2.getTime());
}