java中instant_Instant
我們已經(jīng)講過(guò),計(jì)算機(jī)存儲(chǔ)的當(dāng)前時(shí)間,本質(zhì)上只是一個(gè)不斷遞增的整數(shù)。Java提供的System.currentTimeMillis()返回的就是以毫秒表示的當(dāng)前時(shí)間戳。
這個(gè)當(dāng)前時(shí)間戳在java.time中以Instant類型表示,我們用Instant.now()獲取當(dāng)前時(shí)間戳,效果和System.currentTimeMillis()類似:
import java.time.*;
----
public class Main {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println(now.getEpochSecond()); // 秒
System.out.println(now.toEpochMilli()); // 毫秒
}
}
打印的結(jié)果類似:
1568568760
1568568760316
實(shí)際上,Instant內(nèi)部只有兩個(gè)核心字段:
public final class Instant implements ... {
private final long seconds;
private final int nanos;
}
一個(gè)是以秒為單位的時(shí)間戳,一個(gè)是更精確的納秒精度。它和System.currentTimeMillis()返回的long相比,只是多了更高精度的納秒。
既然Instant就是時(shí)間戳,那么,給它附加上一個(gè)時(shí)區(qū),就可以創(chuàng)建出ZonedDateTime:
// 以指定時(shí)間戳創(chuàng)建Instant:
Instant ins = Instant.ofEpochSecond(1568568760);
ZonedDateTime zdt = ins.atZone(ZoneId.systemDefault());
System.out.println(zdt); // 2019-09-16T01:32:40+08:00[Asia/Shanghai]
可見(jiàn),對(duì)于某一個(gè)時(shí)間戳,給它關(guān)聯(lián)上指定的ZoneId,就得到了ZonedDateTime,繼而可以獲得了對(duì)應(yīng)時(shí)區(qū)的LocalDateTime。
所以,LocalDateTime,ZoneId,Instant,ZonedDateTime和long都可以互相轉(zhuǎn)換:
┌─────────────┐
│LocalDateTime│────┐
└─────────────┘ │ ┌─────────────┐
├───>│ZonedDateTime│
┌─────────────┐ │ └─────────────┘
│ ZoneId │────┘ ▲
└─────────────┘ ┌─────────┴─────────┐
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Instant ││ long │
└─────────────┘ └─────────────┘
轉(zhuǎn)換的時(shí)候,只需要留意long類型以毫秒還是秒為單位即可。
小結(jié)
Instant表示高精度時(shí)間戳,它可以和ZonedDateTime以及l(fā)ong互相轉(zhuǎn)換。
總結(jié)
以上是生活随笔為你收集整理的java中instant_Instant的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c# chart 各个属性_C# Cha
- 下一篇: bat脚本命令