java中Instant類使用詳解(附完整實(shí)例)
前言
Instant 是 Java 8 引入的日期時(shí)間 API 中的一個(gè)核心類,用于表示 時(shí)間線上的一個(gè)瞬時(shí)點(diǎn)(以 Unix 紀(jì)元 1970-01-01T00:00:00Z 為起點(diǎn))。它是不可變的(線程安全),適用于記錄時(shí)間戳、性能分析、跨時(shí)區(qū)事件處理等場(chǎng)景。以下是關(guān)于Instant的詳細(xì)介紹:
一、核心特性
- 不可變性
- 所有操作(如加減、調(diào)整)都會(huì)返回新對(duì)象,原對(duì)象保持不變。
- 線程安全
- 由于不可變性,無(wú)需同步即可安全使用。
- 高精度
- 支持納秒級(jí)精度(
getNano()方法)。
- 支持納秒級(jí)精度(
- UTC 時(shí)間
- 默認(rèn)以 UTC 時(shí)區(qū)表示時(shí)間,不包含時(shí)區(qū)信息。
- 與傳統(tǒng)類的兼容性
- 可與
Date、LocalDateTime、ZonedDateTime等類互轉(zhuǎn)。
- 可與
二、創(chuàng)建Instant實(shí)例
1.now():獲取當(dāng)前時(shí)間的Instant
Instant now = Instant.now();
System.out.println("當(dāng)前時(shí)間: " + now); // 輸出如 2025-05-25T14:34:32.123456789Z
2.ofEpochSecond(long epochSecond):通過(guò)秒數(shù)創(chuàng)建
Instant fromSeconds = Instant.ofEpochSecond(1716549272);
System.out.println("從秒數(shù)創(chuàng)建: " + fromSeconds); // 對(duì)應(yīng) 2025-05-25T14:34:32Z
3.ofEpochMilli(long epochMilli):通過(guò)毫秒數(shù)創(chuàng)建
Instant fromMillis = Instant.ofEpochMilli(1716549272123L);
System.out.println("從毫秒數(shù)創(chuàng)建: " + fromMillis); // 對(duì)應(yīng) 2025-05-25T14:34:32.123Z
4.parse(CharSequence text):解析字符串為Instant
Instant parsed = Instant.parse("2025-05-25T14:34:32.123Z");
System.out.println("解析后的時(shí)間: " + parsed); // 輸出相同時(shí)間
三、獲取時(shí)間戳屬性
1. 獲取秒數(shù)
long seconds = now.getEpochSecond(); // 獲取自1970-01-01T00:00:00Z以來(lái)的秒數(shù)
System.out.println("秒數(shù): " + seconds);
2. 獲取毫秒數(shù)
long millis = now.toEpochMilli(); // 獲取自1970-01-01T00:00:00Z以來(lái)的毫秒數(shù)
System.out.println("毫秒數(shù): " + millis);
3. 獲取納秒數(shù)
int nanos = now.getNano(); // 獲取秒內(nèi)的納秒部分(0~999,999,999)
System.out.println("納秒數(shù): " + nanos);
四、時(shí)間加減操作
1.plusSeconds(long seconds)/minusSeconds(long seconds)
Instant plus10Seconds = now.plusSeconds(10); // 當(dāng)前時(shí)間 + 10秒
Instant minus5Seconds = now.minusSeconds(5); // 當(dāng)前時(shí)間 - 5秒
System.out.println("加10秒: " + plus10Seconds);
System.out.println("減5秒: " + minus5Seconds);
2.plus(Duration duration)/minus(Duration duration)
Duration duration = Duration.ofHours(2); // 2小時(shí)
Instant plus2Hours = now.plus(duration);
Instant minus2Hours = now.minus(duration);
System.out.println("加2小時(shí): " + plus2Hours);
System.out.println("減2小時(shí): " + minus2Hours);
五、與其他時(shí)間類的轉(zhuǎn)換
1. 轉(zhuǎn)換為L(zhǎng)ocalDateTime(需指定時(shí)區(qū))
LocalDateTime localDateTime = now.atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println("本地時(shí)間: " + localDateTime);
2. 轉(zhuǎn)換為ZonedDateTime
ZonedDateTime zonedDateTime = now.atZone(ZoneId.of("Asia/Shanghai"));
System.out.println("帶時(shí)區(qū)的時(shí)間: " + zonedDateTime); // 輸出 2025-05-25T22:34:32.123+08:00[Asia/Shanghai]
3. 轉(zhuǎn)換為Date
Date date = Date.from(now);
System.out.println("轉(zhuǎn)換為Date: " + date);
4. 從Date轉(zhuǎn)換為Instant
Instant fromDate = date.toInstant();
System.out.println("從Date轉(zhuǎn)換: " + fromDate);
六、時(shí)間比較
1.isBefore(Instant other)/isAfter(Instant other)
Instant future = now.plusSeconds(100);
boolean isBefore = now.isBefore(future); // true
System.out.println("是否在目標(biāo)時(shí)間之前: " + isBefore);
2.equals(Instant other):判斷是否相等
Instant sameInstant = now;
boolean isEqual = now.equals(sameInstant); // true
System.out.println("是否相等: " + isEqual);
七、特殊常量與邊界值
1.EPOCH:Unix 紀(jì)元起點(diǎn)
Instant epoch = Instant.EPOCH;
System.out.println("紀(jì)元起點(diǎn): " + epoch); // 1970-01-01T00:00:00Z
2.MIN/MAX:時(shí)間范圍邊界
Instant minInstant = Instant.MIN; // -10^6 - 1970-01-01T00:00:00Z
Instant maxInstant = Instant.MAX; // +10^6 - 1970-01-01T00:00:00Z
System.out.println("最小時(shí)間: " + minInstant);
System.out.println("最大時(shí)間: " + maxInstant);
八、格式化與解析
1. 格式化為字符串
String formatted = now.toString(); // 默認(rèn)格式:2025-05-25T14:34:32.123456789Z
System.out.println("格式化后的時(shí)間: " + formatted);
2. 自定義格式解析
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX");
Instant customParsed = Instant.parse("2025-05-25 14:34:32 +0800", formatter);
System.out.println("自定義解析后的時(shí)間: " + customParsed); // 輸出 UTC 時(shí)間
九、常見用例示例
1. 記錄代碼執(zhí)行時(shí)間
Instant start = Instant.now();
// 執(zhí)行耗時(shí)操作
Thread.sleep(1000);
Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println("耗時(shí): " + duration.toSeconds() + " 秒");
2. 跨時(shí)區(qū)時(shí)間轉(zhuǎn)換
Instant utcTime = Instant.now();
ZonedDateTime newYorkTime = utcTime.atZone(ZoneId.of("America/New_York"));
System.out.println("紐約時(shí)間: " + newYorkTime); // 輸出如 2025-05-25T08:34:32.123-04:00[America/New_York]
3. 處理歷史時(shí)間戳
Instant historicalEvent = Instant.ofEpochSecond(-123456); // 1970年之前的事件
System.out.println("歷史事件時(shí)間: " + historicalEvent); // 輸出如 -0001-12-01T00:00:00Z
十、完整代碼示例
import java.time.*;
import java.time.format.DateTimeFormatter;
public class InstantExample {
public static void main(String[] args) {
// 創(chuàng)建Instant
Instant now = Instant.now();
System.out.println("當(dāng)前時(shí)間: " + now);
// 獲取時(shí)間戳
long seconds = now.getEpochSecond();
long millis = now.toEpochMilli();
int nanos = now.getNano();
System.out.println("秒數(shù): " + seconds + ", 毫秒數(shù): " + millis + ", 納秒數(shù): " + nanos);
// 時(shí)間加減
Instant plus10Sec = now.plusSeconds(10);
Instant minus5Sec = now.minusSeconds(5);
System.out.println("加10秒: " + plus10Sec);
System.out.println("減5秒: " + minus5Sec);
// 轉(zhuǎn)換為其他時(shí)間類
ZonedDateTime zoned = now.atZone(ZoneId.of("Asia/Shanghai"));
LocalDateTime local = zoned.toLocalDateTime();
System.out.println("本地時(shí)間: " + local);
System.out.println("帶時(shí)區(qū)的時(shí)間: " + zoned);
// 時(shí)間比較
Instant future = now.plusSeconds(100);
System.out.println("是否在目標(biāo)時(shí)間之前: " + now.isBefore(future));
// 格式化與解析
String formatted = now.toString();
System.out.println("格式化后的時(shí)間: " + formatted);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX");
Instant parsed = Instant.parse("2025-05-25 14:34:32 +0800", formatter);
System.out.println("解析后的時(shí)間: " + parsed);
}
}
十一、總結(jié)
| 方法 | 用途 |
|---|---|
now() / ofEpochSecond() / ofEpochMilli() / parse() | 創(chuàng)建 Instant 實(shí)例 |
getEpochSecond() / toEpochMilli() / getNano() | 獲取時(shí)間戳屬性 |
plusSeconds() / minusSeconds() / plus() / minus() | 時(shí)間加減操作 |
atZone() / toLocalDateTime() / from(Date) | 轉(zhuǎn)換為其他時(shí)間類 |
isBefore() / isAfter() / equals() | 時(shí)間比較 |
EPOCH / MIN / MAX | 特殊時(shí)間點(diǎn) |
- 優(yōu)勢(shì)
- 高精度:支持納秒級(jí)時(shí)間戳,適合高性能場(chǎng)景。
- 線程安全:不可變?cè)O(shè)計(jì)避免并發(fā)問題。
- 兼容性:與
Date、LocalDateTime等無(wú)縫集成。 - 跨時(shí)區(qū)處理:通過(guò)
atZone()自動(dòng)適配時(shí)區(qū)。
到此這篇關(guān)于java中Instant類使用的文章就介紹到這了,更多相關(guān)java Instant類詳解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用java獲取指定鏈接的網(wǎng)頁(yè)內(nèi)容
Java提供了許多用于網(wǎng)絡(luò)通信的庫(kù),其中最常用的是HttpURLConnection和HttpClient,本文將使用HttpURLConnection進(jìn)行爬取指定鏈接的網(wǎng)頁(yè)內(nèi)容,感興趣的可以了解下2023-09-09
Java并發(fā)編程之詳解ConcurrentHashMap類
在之前的文章中已經(jīng)為大家介紹了java并發(fā)編程的工具:BlockingQueue接口、ArrayBlockingQueue、DelayQueue、LinkedBlockingQueue、PriorityBlockingQueue、SynchronousQueue、BlockingDeque接口,本文為系列文章第八篇.需要的朋友可以參考下2021-06-06
Spring框架基于xml實(shí)現(xiàn)自動(dòng)裝配流程詳解
自動(dòng)裝配就是指?Spring?容器在不使用?<constructor-arg>?和<property>?標(biāo)簽的情況下,可以自動(dòng)裝配(autowire)相互協(xié)作的?Bean?之間的關(guān)聯(lián)關(guān)系,將一個(gè)?Bean?注入其他?Bean?的?Property?中2022-11-11
如何將默認(rèn)的maven倉(cāng)庫(kù)改為阿里的maven倉(cāng)庫(kù)
這篇文章主要介紹了如何將默認(rèn)的maven倉(cāng)庫(kù)改為阿里的maven倉(cāng)庫(kù),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
關(guān)于注解式的分布式Elasticsearch的封裝案例
這篇文章主要介紹了關(guān)于注解式的分布式Elasticsearch的封裝案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-01-01
Spring?Cache注解@Cacheable的九個(gè)屬性詳解
在@Cacheable注解的使用中,共有9個(gè)屬性供我們來(lái)使用,這9個(gè)屬性分別是:value、?cacheNames、?key、?keyGenerator、?cacheManager、?cacheResolver、?condition、?unless、?sync,下面介紹@Cacheable注解屬性使用方法,感興趣的朋友一起看看吧2025-05-05
idea向System.getenv()添加系統(tǒng)環(huán)境變量的操作
這篇文章主要介紹了idea向System.getenv()添加系統(tǒng)環(huán)境變量的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06

