根据两个日期之间获取LocalDate日历列表和LocalDate和LocalDateTime数据格式转换
package com.example.core.mydemo.localdatetime;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* 根据两个日期之间,获取该日期之间的每天的日期格式
* LocalDate和LocalDateTime数据格式转换
* output:
* 2024-10-01
* 2024-10-02
* 2024-10-03
* 2024-10-04
* 2024-10-05
* ldt=2024-05-22T10:00
* ldtStr=2024-05-22 10:00:00
*/
public class LocalDateTest {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
//开始
Long start = 20241001L;
//结束
Long end = 20241005L;
if(start.longValue() == end.longValue()){
LocalDate ldStart = parseStringToLocalDate(String.valueOf(start),"yyyyMMdd");
list.add(formatLocalDateToString(ldStart,"yyyy-MM-dd"));
}else if(start < end){
LocalDate ldStart = parseStringToLocalDate(String.valueOf(start),"yyyyMMdd");
LocalDate ldEnd = parseStringToLocalDate(String.valueOf(end),"yyyyMMdd");
list.add(formatLocalDateToString(ldStart,"yyyy-MM-dd"));
// list.add(formatLocalDateToString(ldEnd,"yyyy-MM-dd"));
LocalDate ldMiddle = ldStart;
while (true){
LocalDate nextDay = ldMiddle.plusDays(1);
list.add(formatLocalDateToString(nextDay,"yyyy-MM-dd"));
//终止循环
if (nextDay.isEqual(ldEnd)) {
break;
}
//递增
ldMiddle = nextDay;
}
}
//默认升序,去重
list = list.stream().distinct().sorted().collect(Collectors.toList());
// Collections.sort(list);
// 输出排序后的列表
for (String str : list) {
System.out.println(str);
}
//LocalDateTime测试
LocalDateTime ldt = parseStringToLocalDateTime("20240522100000","yyyyMMddHHmmss");
System.out.println("ldt=" + ldt);
String ldtStr = formatLocalDateTimeToString(ldt,"yyyy-MM-dd HH:mm:ss");
System.out.println("ldtStr=" + ldtStr);
}
/**
* LocalDate转换
* @param date
* @param format
* @return
*/
public static LocalDate parseStringToLocalDate(String date,String format) {
return LocalDate.parse(date, DateTimeFormatter.ofPattern(format));
}
public static String formatLocalDateToString(LocalDate localDate,String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return localDate.format(formatter);
}
/**
* 同理 LocalDateTime
* @param date
* @param format
* @return
*/
public static LocalDateTime parseStringToLocalDateTime(String date,String format) {
return LocalDateTime.parse(date, DateTimeFormatter.ofPattern(format));
}
public static String formatLocalDateTimeToString(LocalDateTime localDateTime,String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return localDateTime.format(formatter);
}
}