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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具