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

Java 8 引入了新的日期时间 API,位于 java.time 包中,用来替代旧的 Date 和 Calendar 类。这套新 API 更清晰、不可变,并且线程安全。以下是使用新日期时间 API 的基本步骤和常见用法。
使用 LocalDateTime.now() 可获取不带时区的当前日期时间:
LocalDateTime now = LocalDateTime.now();
System.out.println("当前日期时间: " + now);
通过 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);
如果需要包含时区,可使用 ZonedDateTime:
立即学习“Java免费学习笔记(深入)”;
ZonedDateTime zonedNow = ZonedDateTime.now();
System.out.println("带时区的时间: " + zonedNow);
// 指定时区
ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime nyTime = ZonedDateTime.now(zoneId);
System.out.println("纽约时间: " + nyTime);
新 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);
</font>基本上就这些。新日期时间 API 设计直观,推荐在所有 Java 8+ 项目中使用,避免旧 API 的诸多问题。
以上就是请简述编写Java程序,使用新的日期时间API(Lo的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号