LocalDate获取一年月份和开始结束日期

复制代码
 1 import java.time.LocalDate;
 2 import java.time.LocalDateTime;
 3 import java.time.LocalTime;
 4 import java.time.format.DateTimeFormatter;
 5 import java.time.temporal.ChronoUnit;
 6 import java.time.temporal.TemporalAdjusters;
 7 import java.util.ArrayList;
 8 import java.util.List;
 9 
10 public class LocalDateTest {
11 
12     public static void main(String[] args) throws Exception {
13         Integer defaultYear = 2025;
14         //获取一年开始日期
15         LocalDate startDate = LocalDate.of(defaultYear, 1, 1);
16         //获取一年结束日期
17         LocalDate endDate = LocalDate.of(defaultYear, 12, 31);
18 
19         List<LocalDate> manths = getMonthsBetween(startDate, endDate);
20         DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
21         DateTimeFormatter pattern2 = DateTimeFormatter.ofPattern("yyyy.MM");
22         for (LocalDate localDate : manths) {
23             //System.out.println(localDate.getMonthValue());
24             LocalDate firstDayOfMonth = localDate.withDayOfMonth(1);
25             LocalDate lastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
26             // 获取当前月份的开始时间和结束时间(假设开始时间为00:00:00,结束时间为23:59:59)
27             LocalDateTime startOfMonth = LocalDateTime.of(firstDayOfMonth, LocalTime.MIDNIGHT);
28             LocalDateTime endOfMonth = LocalDateTime.of(lastDayOfMonth, LocalTime.MAX);
29             String s2 = firstDayOfMonth.format(pattern2);
30             String s = startOfMonth.format(pattern);
31             String e = endOfMonth.format(pattern);
32 
33             System.out.println(s2 + " " + s + "~" + e);
34 
35         }
36 
37     }
38 
39 
40     public static List<LocalDate> getMonthsBetween(LocalDate start, LocalDate end) {
41         List<LocalDate> months = new ArrayList<>();
42         LocalDate current = start.withDayOfMonth(1);
43         while (current.isBefore(end.plusDays(1)) || current.isEqual(end)) {
44             months.add(current);
45             current = current.plus(1, ChronoUnit.MONTHS);
46         }
47         return months;
48     }
49 
50 }
复制代码

 

复制代码
2025.01 2025-01-01 00:00:00~2025-01-31 23:59:59
2025.02 2025-02-01 00:00:00~2025-02-28 23:59:59
2025.03 2025-03-01 00:00:00~2025-03-31 23:59:59
2025.04 2025-04-01 00:00:00~2025-04-30 23:59:59
2025.05 2025-05-01 00:00:00~2025-05-31 23:59:59
2025.06 2025-06-01 00:00:00~2025-06-30 23:59:59
2025.07 2025-07-01 00:00:00~2025-07-31 23:59:59
2025.08 2025-08-01 00:00:00~2025-08-31 23:59:59
2025.09 2025-09-01 00:00:00~2025-09-30 23:59:59
2025.10 2025-10-01 00:00:00~2025-10-31 23:59:59
2025.11 2025-11-01 00:00:00~2025-11-30 23:59:59
2025.12 2025-12-01 00:00:00~2025-12-31 23:59:59
复制代码

 

posted @   香巴拉  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示