Java程式獲取自Java紀元開始以來的秒數
在這篇文章中,我們將學習如何獲取自Java紀元開始以來的秒數。要獲取自紀元開始以來的秒數,您需要使用Instant。這裡使用的的方法是ofEpochSecond()方法。
紀元是自1970年1月1日星期四00:00:00起經過的秒數。
使用ChronoUnit.SECONDS獲取秒數 -
long seconds = Instant.ofEpochSecond(0L).until(Instant.now(), ChronoUnit.SECONDS);
獲取自紀元開始以來的秒數的步驟
以下是獲取自紀元開始以來的秒數的步驟 -
- 首先,我們將從java.time 和java.time.temporal包中匯入Instant和ChronoUnit類。
- 建立紀元的瞬間並使用Instant.ofEpochSecond(0L)建立表示Java紀元開始(1970年1月1日)的Instant。
- 獲取當前瞬間並使用Instant.now()檢索當前時間。
- 使用until()方法計算經過的秒數,傳遞Instant.now()和ChronoUnit.SECONDS,以計算自紀元開始以來經過的秒數。
- 顯示結果,列印計算出的秒數。
Java程式獲取自紀元開始以來的秒數
以下是獲取自紀元開始以來的秒數的Java程式 -
import java.time.Instant; import java.time.temporal.ChronoUnit; public class Demo { public static void main(String[] args) { long seconds = Instant.ofEpochSecond(0L).until(Instant.now(), ChronoUnit.SECONDS); System.out.println("Seconds since the beginning of the Java epoch = "+seconds); } }
輸出
Seconds since the beginning of the Java epoch = 1555053202
程式碼解釋
在這個程式中,我們使用Java的Instant類處理時間戳,並使用ChronoUnit.SECONDS以秒為單位測量經過的時間。我們首先建立一個Instant物件,表示紀元的開始時間(Instant.ofEpochSecond(0L)),它對應於1970年1月1日。然後,我們呼叫Instant.now()獲取當前時間。使用until()方法,我們計算紀元開始和當前時間之間的秒差。最後,結果列印到控制檯,顯示自紀元開始以來經過的秒數。
廣告