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