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();
}
-
**seconds**
表示从1970-01-01T00:00:00Z
到目前为止经过了多少秒 -
**nanos**
表示从我们获取的这个时间点的这一秒内,已经过了多少纳秒 - 获取当前时间的
**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秒,可见这里也只是精确到了毫秒
- Instant.now()为什么只能精确到毫秒?
前面说到,调用的是System.currentTimeMillis()
方法,这个方法只能返回毫秒,所以使用Instant.now()
声明的实例,肯定是只能表示到毫秒。 - 有没有更精确的方法?
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);
}
网友评论