将毫秒值(currentTimeMillis)转换为(年-月-日 时-分-秒)的形式,只需一行代码

        //首先获取当前的毫秒值
        long currentTimeMillis = System.currentTimeMillis();
        /**
         * 转换为年月日时分秒的形式,得到的currentTime就是转换之后的值了
         * yyyy-MM-dd HH-mm-ss
         * 年-月-日 时-分-秒
         */
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(currentTimeMillis);

如果说你只想要"时-分-秒"

        String currentTime = new SimpleDateFormat("HH-mm-ss").format(currentTimeMillis);
### Java 间戳转换为 `YYYY-MM-dd HH:mm:ss` 格式 在 Java 中,可以通过多种方式将间戳转换为指定的间格式。以下是两种常见的方法: #### 方法一:使用 `java.time` 包 自 Java 8 开始引入了新的期和间 API (`java.time`),推荐优先使用该包下的类来进行期操作。通过 `Instant` 类表示间戳,并结合 `DateTimeFormatter` 来完成格式化。 ```java import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class TimestampToDate { public static void main(String[] args) { long timestamp = System.currentTimeMillis(); // 获取当前间戳(毫秒) Instant instant = Instant.ofEpochMilli(timestamp); // 将间戳转为 Instant 对象 LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime(); // 转换为本地间 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedDate = localDateTime.format(formatter); System.out.println(formattedDate); } } ``` 上述代码展示了如何利用 `java.time` 包中的功能实现间戳到标准格式字符串的转换[^1]。 --- #### 方法二:使用传统 `SimpleDateFormat` 对于较旧版本的 Java 或者某些特定场景下仍需兼容的情况,可以采用传统的 `SimpleDateFormat` 方式处理期格式化问题。 ```java import java.text.SimpleDateFormat; import java.util.Date; public class TimestampToDateLegacy { public static void main(String[] args) { long timestamp = System.currentTimeMillis(); // 获取当前间戳(毫秒) Date date = new Date(timestamp); // 构造 Date 对象 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 定义目标格式 String formattedDate = sdf.format(date); System.out.println(formattedDate); } } ``` 此部代码说明了基于早期 JDK 版本中常用的 `SimpleDateFormat` 实现相同需求的方式[^2]。 --- ### 总结 无论是现代还是经典的解决方案都可以满足将间戳转换成 `YYYY-MM-dd HH:mm:ss` 的要求。然而需要注意的是,在多线程环境下使用 `SimpleDateFormat` 可能会引发线程安全问题;而相比之下,`java.time` 提供了一套更加简洁且线程安全的设计方案[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值