java instant,Java 8 Instant.now()具有纳秒分辨率?

Java 8's java.time.Instant stores in "nanosecond resolution", but using Instant.now() only provides millisecond resolution...

Instant instant = Instant.now();

System.out.println(instant);

System.out.println(instant.getNano());

Result...

2013-12-19T18:22:39.639Z

639000000

How can I get an Instant whose value is 'now', but with nanosecond resolution?

解决方案

While default Java8 clock does not provide nanoseconds resolution, you can combine it with Java ability to measure time differences with nanoseconds resolution, thus creating an actual nanosecond-capable clock.

public class NanoClock extends Clock

{

private final Clock clock;

private final long initialNanos;

private final Instant initialInstant;

public NanoClock()

{

this(Clock.systemUTC());

}

public NanoClock(final Clock clock)

{

this.clock = clock;

initialInstant = clock.instant();

initialNanos = getSystemNanos();

}

@Override

public ZoneId getZone()

{

return clock.getZone();

}

@Override

public Instant instant()

{

return initialInstant.plusNanos(getSystemNanos() - initialNanos);

}

@Override

public Clock withZone(final ZoneId zone)

{

return new NanoClock(clock.withZone(zone));

}

private long getSystemNanos()

{

return System.nanoTime();

}

}

Using it is straightforward: just provide extra parameter to Instant.now(), or call Clock.instant() directly:

final Clock clock = new NanoClock();

final Instant instant = Instant.now(clock);

System.out.println(instant);

System.out.println(instant.getNano());

Although this solution might work even if you re-create NanoClock instances every time, it's always better to stick with a stored clock initialized early in your code, then used wherever it's needed.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值