聊聊如何格式化 Instant
大家好,我是指北君。
今天我們將聊聊如何在Java中把一個(gè) Instant 格式化為一個(gè)字符串。我們將展示如何使用 Java 原生和第三方庫(kù)(如Joda-Time)來(lái)處理這個(gè)事情。
使用 Java 原生格式化Instant
在 Java 8 中有個(gè)名為 Instant 類。通常情況下,我們可以使用這個(gè)類來(lái)記錄我們應(yīng)用程序中的事件時(shí)間戳。
讓我們看看如何把它轉(zhuǎn)換成一個(gè)字符串對(duì)象。
使用 DateTimeFormatter 類
一般來(lái)說(shuō),我們將需要一個(gè)格式化器來(lái)格式化一個(gè)即時(shí)對(duì)象。Java 8引入了DateTimeFormatter類來(lái)統(tǒng)一格式化日期和時(shí)間。
DateTimeFormatter 提供了 format() 方法來(lái)完成這項(xiàng)工作。
簡(jiǎn)單地說(shuō),DateTimeFormatter 需要一個(gè)時(shí)區(qū)來(lái)格式化一個(gè) Instant 。沒(méi)有它,它將無(wú)法將Instant 轉(zhuǎn)換為人類可讀的日期/時(shí)間域。
例如,讓我們假設(shè)我們想用 dd.MM.yyyy 格式來(lái)顯示我們的即時(shí)信息實(shí)例。
public class FormatInstantUnitTest {
private static final String PATTERN_FORMAT = "dd.MM.yyyy";
@Test
public void givenInstant_whenUsingDateTimeFormatter_thenFormat() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT)
.withZone(ZoneId.systemDefault());
Instant instant = Instant.parse("2022-04-21T15:35:24.00Z");
String formattedInstant = formatter.format(instant);
assertThat(formattedInstant).isEqualTo("21.04.2022");
}
}
如上所示,我們可以使用withZone()方法來(lái)指定時(shí)區(qū)。
請(qǐng)記住,如果不能指定時(shí)區(qū)將導(dǎo)致 UnsupportedTemporalTypeException。
@Test(expected = UnsupportedTemporalTypeException.class)
public void givenInstant_whenNotSpecifyingTimeZone_thenThrowException() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT);
Instant instant = Instant.now();
formatter.format(instant);
}
使用toString()方法
另一個(gè)解決方案是使用toString()方法來(lái)獲得即時(shí)對(duì)象的字符串表示。
讓我們用一個(gè)測(cè)試案例舉例說(shuō)明toString()方法的使用。
@Test
public void givenInstant_whenUsingToString_thenFormat() {
Instant instant = Instant.ofEpochMilli(1641828224000L);
String formattedInstant = instant.toString();
assertThat(formattedInstant).isEqualTo("2022-01-10T15:23:44Z");
}
這種方法的局限性在于,我們不能使用自定義的、對(duì)人友好的格式來(lái)顯示即時(shí)信息。
Joda-Time庫(kù)
另外,我們也可以使用 Joda-Time API 來(lái)實(shí)現(xiàn)同樣的目標(biāo)。這個(gè)庫(kù)提供了一套隨時(shí)可用的類和接口,用于在Java中操作日期和時(shí)間。
在這些類中,我們發(fā)現(xiàn)DateTimeFormat類。顧名思義,這個(gè)類可以用來(lái)格式化或解析進(jìn)出字符串的日期/時(shí)間數(shù)據(jù)。
因此,讓我們來(lái)說(shuō)明如何使用DateTimeFormatter來(lái)將一個(gè)瞬間轉(zhuǎn)換為一個(gè)字符串。
@Test
public void givenInstant_whenUsingJodaTime_thenFormat() {
org.joda.time.Instant instant = new org.joda.time.Instant("2022-03-20T10:11:12");
String formattedInstant = DateTimeFormat.forPattern(PATTERN_FORMAT)
.print(instant);
assertThat(formattedInstant).isEqualTo("20.03.2022");
}
我們可以看到,DateTimeFormatter提供forPattern()來(lái)指定格式化模式,print()來(lái)格式化即時(shí)對(duì)象。
總結(jié)
在這篇文章中,我們了解了如何在Java中把一個(gè) Instant 格式化為一個(gè)字符串。
在這一過(guò)程中,我們了解了一些使用Java 原生方法來(lái)實(shí)現(xiàn)這一目標(biāo)的方法。然后,我們解釋了如何使用Joda-Time庫(kù)來(lái)完成同樣的事情。