import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* @Description: 时间切片工具
* @Auther: xuxiaojun
* @Date: 2020-03-19
*/
public class DateSplitUtils {
/**
* 按照指定小时分割时间段
* @param dateType 类型 M/D/H/N -->每月/每天/每小时/每分钟
* @param dBegin开始时间
* @param dEnd结束时间
* @param time 指定小时(如:1、2、3、4)
* @return
*/
public static List<String> findDates(String dateType, Date dBegin, Date dEnd,int time) throws Exception {
List<String> listDate = new ArrayList<>();
listDate.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dBegin));
Calendar calBegin = Calendar.getInstance();
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
calEnd.setTime(dEnd);
while (calEnd.after(calBegin)) {
if ("H".equals(dateType)){
calBegin.add(Calendar.HOUR, time);
}
if ("M".equals(dateType)){
calBegin.add(Calendar.MONTH, time);
}
if ("D".equals(dateType)){
calBegin.add(Calendar.DATE, time);
}
if ("N".equals(dateType)){
calBegin.add(Calendar.MINUTE , time);
}
if (calEnd.after(calBegin)){
listDate.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calBegin.getTime()));
}
else{
// listDate.add(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calEnd.getTime()));
}
}
return listDate;
}
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String startDate = "2021-05-07".concat(" 01:00");
String endDate = "2021-05-07".concat(" 03:00");
Date dBegin = sdf.parse(startDate);
Date dEnd = sdf.parse(endDate);
List<String> list = findDates("N", dBegin, dEnd,30);
int size = list.size();
for (int i = 0; i < size-1; i++) {
System.out.println("开始时间"+list.get(i));
System.out.println("开始时间"+list.get(i+1));
System.out.println();
}
System.out.println("开始时间"+list.get(size-1));
System.out.println("开始时间"+endDate);
}
}
标签:俩个,SimpleDateFormat,add,calBegin,拆分,import,Calendar,dateType,按照
From: https://www.cnblogs.com/xiaoshahai/p/17250883.html