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

在Java中格式化时间戳输出,通常使用 SimpleDateFormat 或 DateTimeFormatter(Java 8+)来将时间戳(long 类型的毫秒值)转换为可读的日期时间字符串。
1. 使用 SimpleDateFormat(适用于 Java 7 及更早版本)
SimpleDateFormat 是 java.text 包下的类,用于格式化和解析日期。可以将时间戳转为指定格式的字符串。
import java.text.SimpleDateFormat;import java.util.Date;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);}}
说明:
“yyyy-MM-dd HH:mm:ss” 是常见的格式,你也可以根据需要调整,例如:
– “dd/MM/yyyy” → 05/12/2024
– “yyyy年MM月dd日 HH时mm分ss秒” → 2024年12月05日 14时30分25秒
2. 使用 DateTimeFormatter(推荐,Java 8+)
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;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());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedTime = dateTime.format(formatter); System.out.println(formattedTime);}}
AI帮个忙
多功能AI小工具,帮你快速生成周报、日报、邮、简历等
116 查看详情
![]()
立即学习“Java免费学习笔记(深入)”;
优点:
- DateTimeFormatter 是不可变对象,线程安全
- 新的时间 API 更清晰、不易出错3. 常见格式符号说明
无论使用哪种格式器,模式字符串含义一致:
yyyy — 年份(如 2024)MM — 月份(01-12)dd — 日期(01-31)HH — 小时(24小时制,00-23)mm — 分钟(00-59)ss — 秒数(00-59)SSS — 毫秒(000-999)
4. 注意事项
使用 SimpleDateFormat 时要注意:
- 它不是线程安全的,多线程环境下建议使用 ThreadLocal 或改用 DateTimeFormatter
- 时间戳单位是毫秒,确保传入的是毫秒值(System.currentTimeMillis())基本上就这些。如果你使用的是 Java 8 或更高版本,优先选择 DateTimeFormatter,代码更简洁也更安全。
以上就是在Java中如何格式化时间戳输出的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/719811.html
微信扫一扫
支付宝扫一扫