1. Overview
1.概述
In this tutorial, we’ll learn how to format an instant to a String in Java.
在本教程中,我们将学习如何在Java中把一个即时数据格式化为String。
First, we’ll start with a bit of background about what an instant is in Java. Then we’ll demonstrate how to answer our central question using core Java and third-party libraries, such as Joda-Time.
首先,我们会先介绍一下Java中的瞬时是什么背景。然后,我们将演示如何使用核心Java和第三方库(如Joda-Time)来回答我们的中心问题。
2. Formatting Instant Using Core Java
2.使用核心Java进行即时格式化
According to the Java documentation, an instant is a measured timestamp from the Java epoch of 1970-01-01T00:00:00Z.
根据Java文档,瞬时是指从1970-01-01T00:00:00Z这个Java纪元开始的一个测量的时间戳。
Java 8 contains a handy class called Instant to represent a specific instantaneous point on the timeline. Typically, we can use this class to record event timestamps in our applications.
Java 8包含一个名为Instant的方便的类,用来表示时间线上的特定瞬时点。通常情况下,我们可以使用这个类来记录我们应用程序中的事件时间戳。
Now that we know what an instant is in Java, let’s see how we can convert it into a String object.
现在我们知道了什么是Java中的瞬间,让我们看看如何将它转换成String对象。
2.1. Using the DateTimeFormatter Class
2.1.使用DateTimeFormatter类
Generally speaking, we’ll need a formatter to format an Instant object. Fortunately for us, Java 8 introduced the DateTimeFormatter class to uniformly format dates and times.
一般来说,我们需要一个格式化器来格式化一个Instant对象。幸运的是,Java 8引入了DateTimeFormatter类来统一格式化日期和时间。
Basically, DateTimeFormatter provides the format() method to do the job.
基本上,DateTimeFormatter提供了format()方法来完成工作。
Simply put, DateTimeFormatter requires a time zone to format an instant. Without it, it’ll fail to convert the instant to human-readable date/time fields.
简单地说,DateTimeFormatter需要一个时区来格式化一个瞬间。没有它,它将无法将瞬间转换为人类可读的日期/时间域。
For instance, let’s suppose we want to display our Instant instance using the dd.MM.yyyy format:
例如,假设我们想用Instant格式来显示我们的Instant实例,dd.MM.yyy。
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");
}
...
}
As shown above, we can use the withZone() method to specify the time zone.
如上所示,我们可以使用withZone()方法来指定时区。
Please bear in mind that failing to specify a time zone will lead to an UnsupportedTemporalTypeException:
请记住,如果没有指定时区,将导致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. Using the toString() Method
2.2.使用toString()方法
Another solution is to use the toString() method to get the string representation of the Instant object.
另一个解决方案是使用toString()方法来获得Instant对象的字符串表示。
Let’s exemplify the use of the toString() method using a test case:
让我们举例说明toString()方法的使用使用一个测试案例。
@Test
public void givenInstant_whenUsingToString_thenFormat() {
Instant instant = Instant.ofEpochMilli(1641828224000L);
String formattedInstant = instant.toString();
assertThat(formattedInstant).isEqualTo("2022-01-10T15:23:44Z");
}
The limitation of this approach is that we can’t use a custom, human-friendly format to display the instant.
这种方法的局限性在于,我们不能使用自定义的、对人类友好的格式来显示即时信息。
3. Joda-Time Library
3.乔达-时间图书馆
Alternatively, we can use the Joda-Time API to achieve the same objective. This library provides a set of ready-to-use classes and interfaces for manipulating the date and time in Java.
另外,我们可以使用Joda-Time API来实现同样的目标。这个库提供了一组随时可用的类和接口,用于在Java中操作日期和时间。
Among these classes, we’ll find the DateTimeFormat class. As the name implies, this class can be used to format or parse date/time data to and from a string.
在这些类中,我们将找到DateTimeFormat类。顾名思义,该类可用于格式化或解析进出字符串的日期/时间数据。
Let’s illustrate how to use DateTimeFormatter to convert an instant into a string:
让我们来说明如何使用DateTimeFormatter 将一个瞬间转换为一个字符串:
@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");
}
As we can see, DateTimeFormatter provides forPattern() to specify the formatting pattern, and print() to format the Instant object.
我们可以看到,DateTimeFormatter提供forPattern()来指定格式化模式,以及print()来格式化Instant对象。
4. Conclusion
4.总结
In this article, we covered in-depth how to format an instant to a string in Java.
在这篇文章中,我们深入介绍了如何在Java中把一个即时信息格式化为一个字符串。
We explored a couple of ways to achieve this using core Java methods. Then we explained how to accomplish the same thing using the Joda-Time library.
我们探讨了使用核心Java方法实现这一目标的几种方法。然后我们解释了如何使用Joda-Time库来完成同样的事情。
As always, the code used in this article can be found over on GitHub.
一如既往,本文中所使用的代码可以在GitHub上找到over。