根據兩個日期之間獲取LocalDate日曆列表

oktokeep發表於2024-05-22

根據兩個日期之間獲取LocalDate日曆列表

package com.example.core.mydemo.localdatetime;

import com.example.core.mydemo.date.LocalDateTimeUtils;
import com.example.core.mydemo.json2.GsonUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class LocalDateTest {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        //開始
        Long start = 20241001L;
        //結束
        Long end = 20241030L;
        if(start.longValue() == end.longValue()){
            LocalDate ldStart = LocalDateTimeUtils.parseStringToLocalDate(String.valueOf(start),"yyyyMMdd");
            list.add(LocalDateTimeUtils.localdateToString(ldStart));
        }else if(start < end){
            LocalDate ldStart = LocalDateTimeUtils.parseStringToLocalDate(String.valueOf(start),"yyyyMMdd");
            LocalDate ldEnd = LocalDateTimeUtils.parseStringToLocalDate(String.valueOf(end),"yyyyMMdd");
            list.add(LocalDateTimeUtils.localdateToString(ldStart));
//            list.add(LocalDateTimeUtils.localdateToString(ldEnd));
            LocalDate ldMiddle = ldStart;
            while (true){
                LocalDate nextDay = ldMiddle.plusDays(1);
                System.out.println("nextDay=" + nextDay);
                list.add(LocalDateTimeUtils.localdateToString(nextDay));
                //終止迴圈
                if (nextDay.isEqual(ldEnd)) {
                    break;
                }
                //遞增
                ldMiddle = nextDay;
            }
        }

        //預設升序
          list =  list.stream().sorted().collect(Collectors.toList());
//        Collections.sort(list);

        // 輸出排序後的列表
        for (String str : list) {
            System.out.println(str);
        }
    }
}


    public static String localdateToString(LocalDate localDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_PATTERN);
        return localDate.format(formatter);
    }
    
    public static LocalDate parseStringToLocalDate(String date,String format) {
        return LocalDate.parse(date, DateTimeFormatter.ofPattern(format));
    }

相關文章