时间戳与格式日期时间转换:LocalDateTime,SimpleDateFormat

该文介绍了在Java中如何使用LocalDateTime进行线程安全的时间戳与格式化日期时间之间的转换,以及使用SimpleDateFormat进行转换但需要注意其线程不安全的问题。
摘要由CSDN通过智能技术生成

时间戳与格式日期时间转换

1.使用LocalDateTime:线程安全

public void testLocalDateTime() {
        long time = new Date().getTime();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //时间戳格式化
        String timeStr = dtf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));
        System.out.println(timeStr);
        //日期字符串转时间戳
        long timeRs = LocalDateTime.from(dtf.parse(timeStr)).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        System.out.println(timeRs);
}

2.使用SimpleDateFormat:线程不安全

public void testSdf() throws ParseException {
        long time = new Date().getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //时间戳格式化
        String timeStr = sdf.format(time);
        System.out.println(timeStr);
        //日期字符串转时间戳
        System.out.println(sdf.parse(timeStr).getTime());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值