请简述编写Java程序,使用新的日期时间API(Lo

Java 8引入java.time包以替代Date和Calendar。1. 使用LocalDateTime.now()获取当前日期时间;2. 通过DateTimeFormatter格式化或解析日期字符串;3. 用ZonedDateTime处理时区,如纽约时间;4. 支持便捷的日期计算,如加减天数、小时等。新API不可变且线程安全,推荐用于Java 8+项目。

Java 8 引入了新的日期时间 API,位于 java.time 包中,用来替代旧的 DateCalendar 类。这套新 API 更清晰、不可变,并且线程安全。以下是使用新日期时间 API 的基本步骤和常见用法。

1. 获取当前日期和时间

使用 LocalDateTime.now() 可获取不带时区的当前日期时间:

LocalDateTime now = LocalDateTime.now();
System.out.println("当前日期时间: " + now);

2. 格式化与解析日期

通过 DateTimeFormatter 进行格式化输出或从字符串解析日期:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(formatter);
System.out.println("格式化后: " + formatted);

LocalDateTime parsed = LocalDateTime.parse("2025-04-05 10:30:00", formatter);
System.out.println("解析后的日期: " + parsed);

3. 处理时区信息

如果需要包含时区,可使用 ZonedDateTime

ZonedDateTime zonedNow = ZonedDateTime.now();
System.out.println("带时区的时间: " + zonedNow);

// 指定时区
ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime nyTime = ZonedDateTime.now(zoneId);
System.out.println("纽约时间: " + nyTime);

4. 日期计算与调整

新 API 提供了方便的方法来加减时间单位:

LocalDateTime tomorrow = now.plusDays(1);
LocalDateTime twoHoursLater = now.plusHours(2);
LocalDateTime lastMonth = now.minusMonths(1);

System.out.println("明天: " + tomorrow);
System.out.println("两小时后: " + twoHoursLater);
System.out.println("上个月: " + lastMonth);

基本上就这些。新日期时间 API 设计直观,推荐在所有 Java 8+ 项目中使用,避免旧 API 的诸多问题。