今天我們將聊聊如何在Java中把一個 Instant 格式化為一個字符串。我們將展示如何使用 Java 原生和第三方庫(如Joda-Time)來處理這個事情。
使用 Java 原生格式化Instant
在 Java 8 中有個名為 Instant 類。通常情況下,我們可以使用這個類來記錄我們應用程序中的事件時間戳。
讓我們看看如何把它轉(zhuǎn)換成一個字符串對象。
使用 DateTimeFormatter 類
一般來說,我們將需要一個格式化器來格式化一個即時對象。Java 8引入了DateTimeFormatter類來統(tǒng)一格式化日期和時間。
DateTimeFormatter 提供了 format() 方法來完成這項工作。
簡單地說,DateTimeFormatter 需要一個時區(qū)來格式化一個 Instant 。沒有它,它將無法將Instant 轉(zhuǎn)換為人類可讀的日期/時間域。
例如,讓我們假設(shè)我們想用 dd.MM.yyyy 格式來顯示我們的即時信息實例。
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()方法來指定時區(qū)。
請記住,如果不能指定時區(qū)將導致 UnsupportedTemporalTypeException。
@Test(expected = UnsupportedTemporalTypeException.class)
public void givenInstant_whenNotSpecifyingTimeZone_thenThrowException() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT);
Instant instant = Instant.now();
formatter.format(instant);
}
使用toString()方法
另一個解決方案是使用toString()方法來獲得即時對象的字符串表示。
讓我們用一個測試案例舉例說明toString()方法的使用。
@Test
public void givenInstant_whenUsingToString_thenFormat() {
Instant instant = Instant.ofEpochMilli(1641828224000L);
String formattedInstant = instant.toString();
assertThat(formattedInstant).isEqualTo("2022-01-10T15:23:44Z");
}
這種方法的局限性在于,我們不能使用自定義的、對人友好的格式來顯示即時信息。
Joda-Time庫
另外,我們也可以使用 Joda-Time API 來實現(xiàn)同樣的目標。這個庫提供了一套隨時可用的類和接口,用于在Java中操作日期和時間。
在這些類中,我們發(fā)現(xiàn)DateTimeFormat類。顧名思義,這個類可以用來格式化或解析進出字符串的日期/時間數(shù)據(jù)。
因此,讓我們來說明如何使用DateTimeFormatter來將一個瞬間轉(zhuǎn)換為一個字符串。
@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()來指定格式化模式,print()來格式化即時對象。
總結(jié)
在這篇文章中,我們了解了如何在Java中把一個 Instant 格式化為一個字符串。
在這一過程中,我們了解了一些使用Java 原生方法來實現(xiàn)這一目標的方法。然后,我們解釋了如何使用Joda-Time庫來完成同樣的事情。
-
JAVA
+關(guān)注
關(guān)注
19文章
2980瀏覽量
105718 -
格式化
+關(guān)注
關(guān)注
2文章
39瀏覽量
9188 -
應用程序
+關(guān)注
關(guān)注
38文章
3305瀏覽量
58212
發(fā)布評論請先 登錄
相關(guān)推薦
評論