java8中的Instant有关

2022年11月22日08:28:12

Instant

表示时间,可以精确到纳秒。
java8中的Instant有关
这里直接打印的时间可以看出来,应该是有时区的差距的,差不多是差了8个小时。
java8中的Instant有关
在 Instant.now()的基础上加上8个小时,打印出来的时间戳就是一致的了。
Instant.ofEpochSecond(ss); 根据给的秒数构建一个对象
Instant.ofEpochSecond(milli); 根据给的毫秒构建一个对象。

本来我想用 now.get(ChronoField.YEAR)获得年份的,但是报错了,后来看源码发现这个方法的参数如果是ChronoField的话就支持四个,
java8中的Instant有关
想找到可以获取到年份的途径,但是都尝试失败了。

now.toEpochMilli() 这个返回值就和 System.currentTimeMillis() 效果是一样的。但是now这个时候是不能加上时区的的
java8中的Instant有关
这就是差别,明显是差了八个小时的。

Duration

可以用来表示一个间隔时间。
java8中的Instant有关
有挺多时间单位可以选择来给构建的。

        Instant now = Instant.now().plus(8,ChronoUnit.HOURS);
        Duration d1 = Duration.ofHours(2);
        Instant now2 = now.plus(d1);
        System.out.println("now = "+now);
        System.out.println("now2 = "+now2);
//        now = 2021-11-09T22:50:03.606Z
//        now2 = 2021-11-10T00:50:03.606Z
        System.out.println("now is before now2 :"+now.isBefore(now2));
        System.out.println("now2 is after now :"+now2.isAfter(now));
//        now is before now2 :true
//        now2 is after now :true

java8中的Instant有关
还可以在Duration的基础上再进行计算。

Period

也是用来表示一段间隔时间的,但是我看的文章上说Period通常用来表示年月日,Duration通常用来表示秒 毫秒的。

java8中的Instant有关

我看静态的构建方法果然就是年月日的,并且这个对象也是可以用Instant对象直接运算的

        Instant now = Instant.now().plus(8,ChronoUnit.HOURS);
        Period p1 = Period.ofDays(1);
        System.out.println(now.plus(p1));
//        2021-11-10T22:56:42.776Z

和Duration的方法有些类似的。

  • 作者:快点到周五
  • 原文链接:https://blog.csdn.net/ZRL1996/article/details/121237959
    更新时间:2022年11月22日08:28:12 ,共 1079 字。