【Java 时间戳】时间戳转格式变1970问题,已解决

前言
好久不见,打工人们!

原因
最近遇到一个新需求,需要获得时间戳(单位是秒),然后转成一定得时间格式,yyyyMMddHHmmss ,本以为不就是 Ctr + C 和 Ctr +V 就能搞定,结果碰壁了。

明明输入时当前时间(0202年),结果一转换就变成了 1970XXXX,这个时间差异太离谱了,没见过。

源代码:

    public static String getFormatTimestamp() {
        // 获取当前时间戳,Java8 新特性
        long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        //时间戳格式转换
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        return df.format(timestamp);
    }

分析
网上搜索了才知道,原来我获取得时间戳单位是秒,而 SimpleDateFormat 转换的时间戳单位需要毫秒,所以得乘 1000L

df.format(timestamp*1000L);

又或者获取时间戳时,直接获取毫秒得时间戳

//获取毫秒数
Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochM

修改后源码
方案1

    public static String getFormatTimestamp() {
        // 当前时间戳
        long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        //时间戳格式转换
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        return df.format(timestamp*1000L);
    }

方案2

    public static String getFormatTimestamp() {
        // 当前时间戳,获取毫秒数
		Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        //时间戳格式转换
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        return df.format(timestamp);
    }

参考文献
Java8 LocalDateTime获取时间戳(毫秒/秒)、LocalDateTime与String互转、Date与LocalDateTime互转
关于时间戳转换时间总是1970的问题

  • 8
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值