根据间隔获取一段时间内的所有时间
public static List<LocalDateTime> getTimeIntervals(LocalDateTime startTime, LocalDateTime endTime, int interval, String intervalType) {
List<LocalDateTime> timeIntervals = new ArrayList<>();
switch (intervalType) {
case "day":
while (!startTime.isAfter(endTime)) {
timeIntervals.add(startTime);
startTime = startTime.plusDays(interval);
}
break;
case "hour":
while (!startTime.isAfter(endTime)) {
timeIntervals.add(startTime);
startTime = startTime.plusHours(interval);
}
break;
case "minute":
while (!startTime.isAfter(endTime)) {
timeIntervals.add(startTime);
startTime = startTime.plusMinutes(interval);
}
break;
case "second":
while (!startTime.isAfter(endTime)) {
timeIntervals.add(startTime);
startTime = startTime.plusSeconds(interval);
}
break;
default:
throw new IllegalArgumentException("Unsupported interval type: " + intervalType);
}
return timeIntervals;
}
public static List<String> getTimeIntervalStrList(LocalDateTime startTime, LocalDateTime endTime, int interval, String intervalType){
List<LocalDateTime> timeIntervals = getTimeIntervals(startTime, endTime, interval, intervalType);
List<String> ss = new ArrayList<>();
for (LocalDateTime t : timeIntervals) {
ss.add(toTimeStr(t));
}
return ss;
}
String,Date,LocalDateTime 之间的转换
public static Date toDate(LocalDateTime a){
ZonedDateTime zonedDateTime = a.atZone(ZoneId.systemDefault());
Instant instant = zonedDateTime.toInstant();
return Date.from(instant);
}
public static LocalDateTime toLocalDateTime(Date a){
Instant instant = a.toInstant();
return LocalDateTime.ofInstant(instant,ZoneId.systemDefault());
}
public static Date getDateByStr(String s){
Date date = new Date();
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(s.contains(" ") ? "yyyy-MM-dd HH:mm:ss" : "yyyy-MM-dd");
date = simpleDateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}finally {
return date;
}
}
public static LocalDateTime getLocalDateTimeByStr(String s){
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(s,df);
}
public static String toTimeStr(LocalDateTime a){
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return a.format(df);
}