推荐使用Java 8的DateTimeFormatter格式化日期时间,配合LocalDateTime或ZonedDateTime实现安全高效输出,如yyyy-MM-dd HH:mm:ss;2. 传统SimpleDateFormat非线程安全,适用于旧版本。

在Java中格式化输出日期与时间,常用的方式是使用 java.time 包中的类(Java 8 及以上推荐)或传统的 SimpleDateFormat。下面介绍几种实用的方法。
Java 8 引入了新的日期时间 API,位于 java.time 包中,配合 DateTimeFormatter 可以安全、高效地格式化日期时间。
示例代码:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(formatter);
System.out.println(formatted); // 输出如:2025-04-05 14:30:22
通过 ofPattern() 方法自定义输出样式,常用符号包括:
立即学习“Java免费学习笔记(深入)”;
例如:
DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm")
// 输出:2025年04月05日 14:30
如果需要显示带时区的时间,可以使用 ZonedDateTime。
import java.time.ZonedDateTime;
import java.time.ZoneId;
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX");
System.out.println(zdt.format(formatter));
// 输出如:2025-04-05 14:30:22 +08:00
在 Java 8 之前,通常使用 SimpleDateFormat 和 Date 类,但该类不是线程安全的,建议封装或使用 ThreadLocal。
import java.text.SimpleDateFormat;
import java.util.Date;
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
基本上就这些。推荐新项目使用 java.time 和 DateTimeFormatter,更清晰、更安全。根据实际需求选择合适的时间类型和格式模板即可。
以上就是在Java中如何格式化输出日期与时间的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号