Java中long类型时间戳与各种时间类型之间的转换


笔者最近在作项目时需要做时间类型和时间戳之间的转换,觉得这一块的内容有时候感觉东一块、西一块的,因此自己想整理一下这两者之间的转换。

1.时间类型转时间戳

  • offsetDateTime转时间戳
        OffsetDateTime time1 = OffsetDateTime.now();
        long timeStamp1 = time1.getLong(ChronoField.INSTANT_SECONDS);	//10位时间戳,按秒
        long timeStamp2 = (Timestamp.valueOf(time1.atZoneSameInstant(ZoneId.of("Z")).toLocalDateTime())).getTime();		//13位时间戳,按毫秒
        System.out.println("时间戳1:"+timeStamp1);
        System.out.println("时间戳2:"+timeStamp2);

打印效果如下:

时间戳1:1627026830
时间戳2:1626998030096

2.时间戳转时间类型

  • 时间戳转offsetDateTime

使用秒级时间戳:

        OffsetDateTime time1 = OffsetDateTime.now();
        long timeStamp1 = time1.getLong(ChronoField.INSTANT_SECONDS);
        LocalDateTime localDateTime1 = Instant.ofEpochSecond(timeStamp1).atOffset(ZoneOffset.UTC).toLocalDateTime();
        OffsetDateTime dateTime1 = OffsetDateTime.of(localDateTime1, ZoneOffset.UTC);
        System.out.println(dateTime1);

​ 打印如下:

2021-07-23T11:06:48Z

使用毫秒级时间戳:

    OffsetDateTime time1 = OffsetDateTime.now();
    long timeStamp2 = (Timestamp.valueOf(time1.atZoneSameInstant(ZoneId.of("Z")).toLocalDateTime())).getTime();
    LocalDateTime localDateTime2 = Instant.ofEpochSecond(timeStamp2).atOffset(ZoneOffset.UTC).toLocalDateTime();
    OffsetDateTime dateTime2 = OffsetDateTime.of(localDateTime2, ZoneOffset.UTC);
    System.out.println(dateTime2);

​ 打印如下:

2021-07-23T03:06:48.341Z

参考文章:

时间戳和LocalDateTime和Date互转和格式化

java - Convert OffsetDateTime to UTC Timestamp - Stack Overflow


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM