localDateTime、Instant 、date间的关系

 LocalDateTime:个人认为这就是本地的日期时间格式对象

Date: 这也是一个本地的日期格式对象,和LocalDateTime不同,LocalDateTime提供了更丰富的处理时间的方法,同时LocalDateTime是线程安全的

Instant:这个一个默认为UTC时区的时间对象,和咱们平常的东八区相比,少了8个小时的时间。

        // 本地时间当前日期时间
        System.out.println(LocalDateTime.now());
        // UTC时区当前日期时间
        System.out.println(Instant.now());
        // 本地时间转换为UTC时区时间 东八区减去八个小时
        System.out.println( LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)));
        System.out.println(                             LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
        // 本地时间转换为UTC时区时间,取出毫秒数
        Long times1 = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        // 直接取出当前UTC时区时间,取出毫秒数(和上面等价)
        Long times2 = Instant.now().toEpochMilli();
        System.out.println(times1);
        System.out.println(times2);
        Date date = new Date();
        System.out.println("date::" + date);
        System.out.println(date.getTime());
        // date转换时转换的就是UTC时间,比如 date的时间(Sun Dec 18 21:18:21 CST 2022)
        // 比date.toInstant() 时间(2022-12-18T13:18:21.573Z)早了8个小时,当前时区东八区
        System.out.println("date.toInstant()::" + date.toInstant());
        System.out.println(date.toInstant().toEpochMilli());
        System.out.println(ZoneId.systemDefault());
        System.out.println(ZoneId.of("UTC"));
        // Instant.now().toEpochMilli()虽然返回的是UTC时间的毫秒数,
        // 但是Date的getTime实际上获取的也是这个时间
        // 因此这个最终返回的是东八区的当前时间
        System.out.println(new Date(Instant.now().toEpochMilli()));

LocalDateTime 转 Date 、Instant转Date

思路就是使用Date.from(instant)方法,直接进行转化既可。LocalDateTime转化为Instant,然后进行转化。

        Instant now = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8));
        System.out.println(Date.from(now));

 Date转LocalDateTime、Date转Instant

        Date date = new Date();
        LocalDateTime time = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        // 输出结果2022-12-18T21:52:59.842
        System.out.println(time);
        LocalDateTime time3 = date.toInstant().atZone(ZoneId.of("UTC")).toLocalDateTime();
        // 输出结果2022-12-18T13:52:59.842
        System.out.println(time3);

虽然没用过,但是觉得这个Instant不太会直接使用,作为一个中间的桥梁转换使用的应该较多。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值