当前位置: 首页 > 科技观察

下面说一下如何格式化Instant

时间:2023-03-13 06:58:30 科技观察

大家好,我是北君。今天我们将讨论如何在Java中将Instant格式化为String。我们将展示如何使用Java本机和第三方库(如Joda-Time)来执行此操作。使用Java的原生格式Instant在Java8中有一个名为Instant的类。通常,我们可以使用这个类来记录我们应用程序中的事件时间戳。让我们看看如何将其转换为字符串对象。使用DateTimeFormatter类通常,我们需要一个格式化程序来格式化即时对象。Java8引入了DateTimeFormatter类来统一格式化日期和时间。DateTimeFormatter提供了format()方法来完成这项工作。简单地说,DateTimeFormatter需要一个时区来格式化一个Instant。没有它,它将无法将Instant转换为人类可读的日期/时间字段。例如,假设我们要以dd.MM.yyyy格式显示我们的即时消息实例。公共类FormatInstantUnitTest{privatestaticfinalStringPATTERN_FORMAT="dd.MM.yyyy";@TestpublicvoidgivenInstant_whenUsingDateTimeFormatter_thenFormat(){DateTimeFormatterformatter=DateTimeFormatter.ofPattern(PATTERN_FORMAT).withZone(ZoneId.systemDefault)stInst=parse("2022-04-21T15:35:24.00Z");StringformattedInstant=formatter.format(instant);assertThat(formattedInstant).isEqualTo("21.04.2022");}}如上所示,我们可以使用withZone()方法来指定时区。请记住,未能指定时区将导致UnsupportedTemporalTypeException。@Test(expected=UnsupportedTemporalTypeException.class)publicvoidgivenInstant_whenNotSpecifyingTimeZone_thenThrowException(){DateTimeFormatter格式化程序=DateTimeFormatter.ofPattern(PATTERN_FORMAT);即时instant=Instant.now();解决方案是使用toString()方法获取即时对象的字符串表示形式。让我们用一个测试用例来说明toString()方法的用法。@TestpublicvoidgivenInstant_whenUsingToString_thenFormat(){Instantinstant=Instant.ofEpochMilli(1641828224000L);StringformattedInstant=instant.toString();assertThat(formattedInstant).isEqualTo("2022-01-10T15:23:44Z")的一个限制是我们无法以自定义的、人性化的格式显示即时消息。Joda-Time库或者,我们可以使用Joda-TimeAPI来实现相同的目标。这个库提供了一组随时可用的类和接口,用于在Java中操作日期和时间。在这些类中,我们找到了DateTimeFormat类。顾名思义,此类可用于格式化或解析字符串中的日期/时间数据。因此,让我们说明如何使用DateTimeFormatter将即时转换为字符串。@TestpublicvoidgivenInstant_whenUsingJodaTime_thenFormat(){org.joda.time.Instantinstant=neworg.joda.time.Instant("2022-03-20T10:11:12");StringformattedInstant=DateTimeFormat.forPattern(PATTERN_FORMAT).print(即时);assertThat(formattedInstant).isEqualTo("20.03.2022");}我们可以看到DateTimeFormatter提供了forPattern()来指定格式模式和print()来格式化即时对象。总结在本文中,我们学习了如何在Java中将Instant格式化为String。在此过程中,我们研究了一些使用Java的本机方法来完成此操作的方法。然后我们解释了如何使用Joda-Time库来完成同样的事情。