LocalDate和LocalDateTime是Java 8引入的不可变、线程安全的日期时间类,分别表示无时区的日期和日期时间,支持创建、解析、加减、格式化及与其他类型互转操作,结合DateTimeFormatter可处理自定义格式,推荐用于新项目。

Java 8 引入了新的日期时间 API,位于 java.time 包中,其中 LocalDate 和 LocalDateTime 是最常用的类。它们是不可变的、线程安全的,使用起来更加直观和方便。
LocalDate 表示一个不带时区的日期,比如 2025-04-05。
• 创建当前日期:LocalDate today = LocalDate.now();
• 指定年月日创建:LocalDate date = LocalDate.of(2025, 4, 5);
立即学习“Java免费学习笔记(深入)”;
• 解析字符串日期:LocalDate parsed = LocalDate.parse("2025-04-05");
• 获取年、月、日:int year = date.getYear();
int month = date.getMonthValue();
int day = date.getDayOfMonth();
• 日期加减操作:LocalDate tomorrow = today.plusDays(1);
LocalDate nextMonth = today.plusMonths(1);
LocalDate lastYear = today.minusYears(1);
• 判断日期前后:boolean isAfter = today.isAfter(parsed);
boolean isBefore = today.isBefore(parsed);
LocalDateTime 表示不带时区的日期和时间,精确到纳秒,比如 2025-04-05T10:30:45。
• 创建当前日期时间:LocalDateTime now = LocalDateTime.now();
• 指定年月日时分秒创建:LocalDateTime dt = LocalDateTime.of(2025, 4, 5, 10, 30, 0);
• 从 LocalDate 转换:LocalDateTime fromLocalDate = today.atTime(12, 0);
• 解析字符串(ISO 格式):LocalDateTime parsedDT = LocalDateTime.parse("2025-04-05T14:20:30");
• 提取日期或时间部分:LocalDate datePart = now.toLocalDate();
LocalTime timePart = now.toLocalTime();
• 时间加减操作:LocalDateTime later = now.plusHours(3);
LocalDateTime earlier = now.minusMinutes(15);
LocalDateTime nextWeek = now.plusWeeks(1);
默认的 parse 和 toString 使用 ISO 标准格式。如果需要处理如 "2025/04/05" 或 "2025-04-05 10:30" 这样的格式,需使用 DateTimeFormatter。
• 定义格式并解析:DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate customDate = LocalDate.parse("2025/04/05", formatter);
• 格式化输出:String formatted = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); // 输出:2025-04-05 10:30
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
• Instant 转 LocalDateTime:LocalDateTime fromInstant = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
• 与旧版 Date 互转:Date date = Date.from(instant);
LocalDateTime back = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
基本上就这些。LocalDate 和 LocalDateTime 简洁易用,配合 DateTimeFormatter 可满足大多数场景需求,推荐在新项目中优先使用。
以上就是java怎么处理日期和时间 操作LocalDate与LocalDateTime的常用方法的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号