将10位或13位时间戳转换为日期+时间--yyyy-MM-dd HH:mm:ss

将10位或13位时间戳转换为日期+时间–yyyy-MM-dd HH:mm:ss

    public static void main(String[] args) {
        //	10位	秒时间戳 		转换
        String date_one = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(toInt("1587467078") * 1000L));//2020-04-21 19:04:38
        System.out.println("10位秒时间戳      1587467078  转换后为:   "+date_one);
        //	13位	毫秒级时间戳 		转换
        String date_two = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss").format(new Date(Long.parseLong("1587469418125")));//2020-04-21 19:04:38
        System.out.println("13位毫秒时间戳 1587469418125  转换后为:   "+date_two);
    }

更多精彩,请点击此链接✈✈✈✈✈✈

### 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、付费专栏及课程。

余额充值