Java中格式化时间戳推荐使用DateTimeFormatter(Java 8+),线程安全且简洁;旧版本可用SimpleDateFormat,但非线程安全。

在Java中格式化时间戳输出,通常使用 SimpleDateFormat 或 DateTimeFormatter(Java 8+)来将时间戳(long 类型的毫秒值)转换为可读的日期时间字符串。
SimpleDateFormat 是 java.text 包下的类,用于格式化和解析日期。可以将时间戳转为指定格式的字符串。
import java.text.SimpleDateFormat;
import java.util.Date;
<p>public class TimestampFormat {
public static void main(String[] args) {
long timestamp = System.currentTimeMillis(); // 示例时间戳
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedTime = sdf.format(new Date(timestamp));
System.out.println(formattedTime);
}
}</p>说明:
"yyyy-MM-dd HH:mm:ss" 是常见的格式,你也可以根据需要调整,例如:
- "dd/MM/yyyy" → 05/12/2024
- "yyyy年MM月dd日 HH时mm分ss秒" → 2024年12月05日 14时30分25秒
Java 8 引入了新的时间 API(java.time 包),更安全、线程友好。推荐使用 Instant、LocalDateTime 或 ZonedDateTime 配合 DateTimeFormatter。
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
<p>public class ModernTimestampFormat {
public static void main(String[] args) {
long timestamp = System.currentTimeMillis();
Instant instant = Instant.ofEpochMilli(timestamp);
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());</p><pre class='brush:java;toolbar:false;'> DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedTime = dateTime.format(formatter);
System.out.println(formattedTime);
}}
立即学习“Java免费学习笔记(深入)”;
优点:
- DateTimeFormatter 是不可变对象,线程安全
- 新的时间 API 更清晰、不易出错
无论使用哪种格式器,模式字符串含义一致:
使用 SimpleDateFormat 时要注意:
- 它不是线程安全的,多线程环境下建议使用 ThreadLocal 或改用 DateTimeFormatter
- 时间戳单位是毫秒,确保传入的是毫秒值(System.currentTimeMillis())
基本上就这些。如果你使用的是 Java 8 或更高版本,优先选择 DateTimeFormatter,代码更简洁也更安全。
以上就是在Java中如何格式化时间戳输出的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号