在Java中将Instant格式化为字符串

807 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第29天,点击查看活动详情

1. 概述

本文我们了解一下Java中如何将Instant格式化为字符串。

首先我们了解一下Java中Instant的基础知识,然后我们再用Java类库和第三方类库来格式化它。

2. Java中格式化Instant

根据Java文件描述,instant就是从1970-01-01T00:00:00Z到现在的一个时间戳。

Java8包含一个名为Instant的类,用于表示时间轴上的特定瞬时点。通常,我们可以使用此类来记录应用中事件的时间戳。

现在我们大概了解了Java中的Instant是什么么,下面让我们看一下如何将它转换为String对象。

2.1. 使用 DateTimeFormatter

一般来说,我们需要定义一个formatter来格式化Instant对象,幸运的是,Java8引入了DateTimeFormatter类来统一格式化日期和时间。

基本上,DateTimeFormatter提供了format()来完成这项工作。

简单来说,DateTimeFormatter需要指定时区然后再格式化Instant,没有时区,它将无法即里转换为人类可读的日期/时间字段。

如何,假设我们使用dd.MM.yyyy格式来显示Instant实例

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-02-15T18:35:24.00Z");
        String formattedInstant = formatter.format(instant);

        assertThat(formattedInstant).isEqualTo("15.02.2022");
    }
    ...
}

如上所述,我们使用withZone()方法来指定时区。

注意:如果没有指定时区会报异常:UnsupportedTemporalTypeException

@Test(expected = UnsupportedTemporalTypeException.class)
public void givenInstant_whenNotSpecifyingTimeZone_thenThrowException() {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT);

    Instant instant = Instant.now();
    formatter.format(instant);
}

2.2. 使用 toString()

另一种方法是使用toString()来返回Instant对象的字符串表示形式。

让我们来用一个测试用例来举例说明toString()方法的使用:

@Test
public void givenInstant_whenUsingToString_thenFormat() {
    Instant instant = Instant.ofEpochMilli(1641828224000L);
    String formattedInstant = instant.toString();

    assertThat(formattedInstant).isEqualTo("2022-01-10T15:23:44Z");
}

这种方法的局限是格式固定了,我们不能使用片定义的、人性化的格式来显示。

3. 第三方库:Joda-Time

我们可以使用Joda-Time API来达到同样的目的。这个库提供了一组随时可用的类和接口,用于在Java中操作日期和时间。

在这些类中,有个DateTimeFormat类,顾名思义,这个类用于格式化日期/时间数据或将日期/时间数据解析为字符串。

下面让我们来说明如何使用DateTimeFormatter将Instant转换为字符串

@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");
}

正如我们所见,DateTimeFormat提供forPattern来指定格式化模式,并提供print()来格式化Instant对象。

4. 结论

在本文中,我们了解了如何在Java中将Instant格式化为字符串。

我们探索了几种使用Java方法来实现此目的的方法以及解释了如何使用Joda-Time库完成同样的事情。