Java时间 之 Instant

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

官方说明精捡

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

类里面主要有什么


    /**
     * The number of seconds from the epoch of 1970-01-01T00:00:00Z.
     */
    private final long seconds;
    /**
     * The number of nanoseconds, later along the time-line, from the seconds field.
     * This is always positive, and never exceeds 999,999,999.
     */
    private final int 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
     */
    public static Instant now() {
        return Clock.systemUTC().instant();
    }
  1. **seconds**表示从1970-01-01T00:00:00Z到目前为止经过了多少秒
  2. **nanos**表示从我们获取的这个时间点的这一秒内,已经过了多少纳秒
  3. 获取当前时间的**Instant**,最后调用的是System.currentTimeMillis()

实例

    public static void main(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. 有没有更精确的方法?
    public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) {
        long secs = Math.addExact(epochSecond, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
        int nos = (int)Math.floorMod(nanoAdjustment, NANOS_PER_SECOND);
        return create(secs, nos);
    }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值