將紀元時間轉換為 LocalDate 和 LocalDateTime
瀏覽人數:812最近更新:
一、簡介
新紀元時間,也稱為 Unix 時間,是一種將日期和時間表示為單個數值的系統。它測量自 1970 年 1 月 1 日 00:00:00 協調世界時 (UTC) 以來經過的毫秒數。紀元時間因其簡單性和易於操作性而廣泛應用於計算機系統和編程語言中。
在本教程中,我們將探討以毫秒為單位的紀元時間到LocalDate
和LocalDateTime
的轉換。
2. 將紀元時間轉換為LocalDate
要將紀元時間轉換為LocalDate
,我們需要將以毫秒為單位的紀元時間轉換為Instant
對象。
Instant
表示 UTC 時區時間線上的一個點:
long epochTimeMillis = 1624962431000L; // Example epoch time in milliseconds
Instant instant = Instant.ofEpochMilli(epochTimeMillis);
獲得Instant
對像後,我們可以通過使用atZone()
方法指定時區並提取日期部分,將其轉換為LocalDate
對象:
ZoneId zoneId = ZoneId.systemDefault(); // Use the system default time zone
LocalDate localDate = instant.atZone(zoneId).toLocalDate();
最後,我們可以以人類可讀的格式輸出轉換後的LocalDate
對象:
System.out.println(localDate); // Output: 2021-06-29
我們可以通過DateTimeFormatter
類使用特定模式來格式化日期:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = localDate.format(formatter);
System.out.println(formattedDate); // Output: 2021-06-29
我們可以根據需要選擇不同的圖案。
這是腳本的表示:
long epochTimeMillis = 1624962431000L; // Example epoch time in milliseconds
Instant instant = Instant.ofEpochMilli(epochTimeMillis);
ZoneId zoneId = ZoneId.systemDefault(); // Use the system default time zone
LocalDate localDate = instant.atZone(zoneId).toLocalDate();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = localDate.format(formatter);
System.out.println(formattedDate); // Output: 2021-06-29
使用這四個步驟,我們可以輕鬆地將紀元時間(以毫秒為單位)轉換為LocalDate
,甚至指定輸出格式。
3. 將紀元時間轉換為LocalDateTime
將紀元時間(以毫秒為單位)轉換為LocalDateTime
的步驟與上面的LocalDate
示例類似。唯一的區別是我們將導入LocalDateTime
類。
將所有內容放在一起,這是轉換為LocalDateTime
腳本:
long epochTimeMillis = 1624962431000L; // Example epoch time in milliseconds
Instant instant = Instant.ofEpochMilli(epochTimeMillis);
ZoneId zoneId = ZoneId.systemDefault(); // Use the system default time zone
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = localDateTime.format(formatter);
System.out.println(formattedDateTime); // Output: 2021-06-29 12:13:51
該腳本將以毫秒為單位的紀元時間轉換為LocalDateTime
,我們可以使用DateTimeFormatter
類格式化日期和時間。
4。結論
在本文中,我們探討了紀元時間(以毫秒為單位)到LocalDate
和LocalDateTime
的轉換。這是一個相當簡單的過程,我們使用DateTimeFormatter
類將輸出轉換為特定的日期或時間格式。
本文的完整實現可以在 GitHub 上找到。
本作品係原創或者翻譯,採用《署名-非商業性使用-禁止演繹4.0國際》許可協議