【Java-Day18】API篇-时间类(新版时间类:LocalDateTime/DateTimeFormatter/LocalDate / LocalDateTime)
2026/6/2 14:52:40 网站建设 项目流程

新版时间类创建的时间日期对象都是不可变的。解决了旧版时间类在多线程环境下会导致数据安全的问题。

LocalDate、LocalTime、LocalDateTime:

方法名说明
static XXX now()获取当前时间的对象
static XXX of(...)获取指定时间的对象
get 开头的方法获取日历中的年、月、日、时、分、秒等信息
isBefore()、isAfter()比较两个时间对象
with 开头的方法修改时间系列的方法
minus 开头的方法减少时间系列的方法
plus 开头的方法增加时间系列的方法
方法名说明
public LocalDate toLocalDate()将 LocalDateTime 转换成一个 LocalDate 对象
public LocalTime toLocalTime()将 LocalDateTime 转换成一个 LocalTime 对象

一.LocalDate

LocalDate 只表示日期:年、月、日。

LocalDate today = LocalDate.now(); System.out.println(today);//2026-06-02

常用方法:

LocalDate date = LocalDate.now(); System.out.println(date.getYear()); // 年 2026 System.out.println(date.getMonthValue()); // 月 6 System.out.println(date.getDayOfMonth()); // 日 2 System.out.println(date.plusDays(10)); // 10天后 2026-06-12 System.out.println(date.minusDays(10)); // 10天前 2026-05-23

二.LocalTime

LocalTime 只表示时间:时、分、秒。

LocalTime time = LocalTime.now(); System.out.println(time); //12:39:06.106026100

三.LocalDateTime

LocalDateTime 同时表示日期和时间。这是最常用的新时间类之一。

LocalDateTime now = LocalDateTime.now(); System.out.println(now);//2026-06-02T12:40:30.737543600

如果不想要中间的 T,就需要格式化。

四.DateTimeFormatter 格式化新时间类

LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String result = now.format(formatter); System.out.println(result);//2026-06-02 12:42:23

字符串转 LocalDateTime:

String str = "2026-06-01 20:30:15"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime time = LocalDateTime.parse(str, formatter); System.out.println(time);//2026-06-01T20:30:15

五.计算时间差

如果计算两个日期相差多少天,可以用 Period。

LocalDate start = LocalDate.of(2026, 6, 1); LocalDate end = LocalDate.of(2026, 6, 10); Period period = Period.between(start, end); System.out.println(period.getDays()); // 9

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询