Java时间 之 Instant

2022年12月2日10:28:39

Instant是一种表示秒和毫秒的类>Instant是Java8中新提供的时间类,出场次数较少,但是小身板里也有一些需要注意的东西

官方说明精捡

  • 这个类在时间线上模拟一个瞬时点(相当于流动的河水中我们舀出来了一瓢,舀出来之后就是静止的)
  • 可用于记录事件的时间戳
  • 这个类不可变,并且线程安全

类里面主要有什么

/**
     * The number of seconds from the epoch of 1970-01-01T00:00:00Z.
     */privatefinallong seconds;/**
     * The number of nanoseconds, later along the time-line, from the seconds field.
     * This is always positive, and never exceeds 999,999,999.
     */privatefinalint nanos;//-----------------------------------------------------------------------/**
     * Obtains the current instant from the system clock.
     * <p>
     * This will query the {@link Clock#systemUTC() system UTC clock} to
     * obtain the current instant.
     * <p>
     * Using this method will prevent the ability to use an alternate time-source for
     * testing because the clock is effectively hard-coded.
     *
     * @return the current instant using the system clock, not null
     */publicstatic Instantnow(){return Clock.systemUTC().instant();}
  1. **seconds**表示从1970-01-01T00:00:00Z到目前为止经过了多少秒
  2. **nanos**表示从我们获取的这个时间点的这一秒内,已经过了多少纳秒
  3. 获取当前时间的**Instant**,最后调用的是System.currentTimeMillis()

实例

publicstaticvoidmain(String[] args){
        Instant instant= Instant.now();
        System.out.println(instant.getEpochSecond());
        System.out.println(instant.getNano());}// OUT// 1564569225      =====> 北京时间:2019/7/31 18:33:45// 346000000       =====> 秒:0.346秒,可见这里也只是精确到了毫秒
  1. Instant.now()为什么只能精确到毫秒?
    前面说到,调用的是System.currentTimeMillis()方法,这个方法只能返回毫秒,所以使用Instant.now()声明的实例,肯定是只能表示到毫秒。
  2. 有没有更精确的方法?
publicstatic InstantofEpochSecond(long epochSecond,long nanoAdjustment){long secs= Math.addExact(epochSecond, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));int nos=(int)Math.floorMod(nanoAdjustment, NANOS_PER_SECOND);returncreate(secs, nos);}

我的个人博客,有空来坐坐

  • 作者:躺在家里不干活
  • 原文链接:https://blog.csdn.net/weixin_29491885/article/details/100129833
    更新时间:2022年12月2日10:28:39 ,共 1542 字。