1. Introduction
1.导言
In this tutorial, we’ll look at several methods for obtaining the current timestamp value in Java and using it as a filename.
在本教程中,我们将学习几种在 Java 中获取当前时间戳值并将其用作文件名的方法。
To accomplish our goal, we’ll leverage several classes from the Java DateTime API and third-party libraries such as Joda-Time.
为了实现我们的目标,我们将利用 Java DateTime API 和第三方库(如 Joda-Time )中的多个类。
2. Initial Setup
2.初始设置
In later sections, we’ll build several test cases showcasing each approach for acquiring the current timestamp and using it as a filename.
在后面的章节中,我们将建立几个测试用例,展示获取当前时间戳并将其用作文件名的每种方法。
However, to convert the timestamp value into a specified string format, we first need to specify the timestamp format and then use it to define the formatter classes:
不过,要将时间戳值转换为指定的字符串格式,我们首先需要指定时间戳格式,然后使用它来定义格式器类:
static final String TIMESTAMP_FORMAT = "yyyyMMddHHmmss";
static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern(TIMESTAMP_FORMAT);
static final SimpleDateFormat SIMPLEDATE_FORMAT = new SimpleDateFormat(TIMESTAMP_FORMAT);
Following that, we’ll write a method that converts the current time value into a valid filename. The sample output of this method will look like “20231209122307.txt“:
接下来,我们将编写一个方法,将当前时间值转换为有效的文件名。该方法的输出示例将显示为”20231209122307.txt“:
String getFileName(String currentTime) {
return MessageFormat.format("{0}.txt", currentTime);
}
Since we’re writing test cases, we’ll create another method to check whether the output filename contains a timestamp with the correct format:
由于我们正在编写测试用例,我们将创建另一个方法来检查输出文件名是否包含格式正确的时间戳:
boolean verifyFileName(String fileName) {
return Pattern
.compile("[0-9]{14}+\\.txt", Pattern.CASE_INSENSITIVE)
.matcher(fileName)
.matches();
}
In this scenario, our filename is composed of numbers that represent the timestamp. It’s advised to ensure that the filename format avoids using characters that are forbidden in file names, which are specific to the respective operating system.
在这种情况下,我们的文件名由代表时间戳的数字组成。建议确保文件名格式避免使用文件名中禁止使用的字符,这些字符是各操作系统特有的。
3. Current Time With Java DateTime API
3.使用 Java DateTime API 获取当前时间
Java supplies legacy classes such as Calendar and Date to deal with date and time information. However, due to design flaws, new classes were introduced with the Java 8 DateTime API. The Date, Calendar, and SimpleDateFormatter classes are mutable and not thread-safe.
Java 提供 Calendar 和 Date 等传统类来处理日期和时间信息。但是,由于设计缺陷,Java 8 DateTime API 引入了新的类。Date、Calendar 和 SimpleDateFormatter 类是可变的,并且不是线程安全的。
We’ll first take a look at the legacy classes Calendar and Date to generate the timestamp and gain a basic understanding, followed by Java 8 DateTime API classes like Instant, LocalDateTime, ZonedDateTime, and OffsetDateTime.
我们将首先查看传统类 Calendar 和 Date 以生成时间戳并获得基本了解,然后查看 Java 8 DateTime API 类,如 Instant、LocalDateTime、ZonedDateTime、 和 OffsetDateTime 等。
Notably, using the Java 8 DateTime API classes is recommended over legacy Java date and time classes for newer Java programs.
值得注意的是,对于较新的 Java 程序,建议使用 Java 8 DateTime API 类,而不是传统的 Java 日期和时间类。
3.1. Using Calendar
3.1.使用日历</em
The most basic approach is to use the Calendar.getInstance() method that returns a Calendar instance using the default time zone and locale. Furthermore, the getTime() method gives us the time value in milliseconds:
最基本的方法是使用 Calendar.getInstance() 方法,该方法使用默认时区和地域返回 Calendar 实例。此外,getTime() 方法还提供了以毫秒为单位的时间值:
@Test
public void whenUsingCalender_thenGetCurrentTime() {
String currentTime = SIMPLEDATE_FORMAT.format(Calendar.getInstance().getTime());
String fileName = getFileName(currentTime);
assertTrue(verifyFileName(fileName));
}
The SimpleDateFormatter class can transform the time value into the appropriate timestamp format.
SimpleDateFormatter 类可将时间值转换为适当的时间戳格式。
3.2. Using Date
3.2.使用日期</em
Similarly, we may construct an object of the Date class that expresses the object’s creation time in milliseconds. SimpleDateFormatter transforms the millisecond time value to the desired string pattern:
同样,我们可以构建一个 Date 类对象,用毫秒来表示对象的创建时间。SimpleDateFormatter 将毫秒时间值转换为所需的字符串模式:
@Test
public void whenUsingDate_thenGetCurrentTime() {
String currentTime = SIMPLEDATE_FORMAT.format(new Date());
String fileName = getFileName(currentTime);
assertTrue(verifyFileName(fileName));
}
It’s recommended to use the new Java 8 classes that we’ll see in the next sections.
建议使用我们将在接下来的章节中介绍的 Java 8 新类。
3.3. Using Instant
3.3.使用即时</em
In Java, the Instant class represents a single moment on the UTC timeline:
在 Java 中,Instant 类表示 UTC 时间轴上的一个时刻:
@Test
public void whenUsingInstant_thenGetCurrentTime() {
String currentTime = Instant
.now()
.truncatedTo(ChronoUnit.SECONDS)
.toString()
.replaceAll("[:TZ-]", "");
String fileName = getFileName(currentTime);
assertTrue(verifyFileName(fileName));
}
Instant.now() method asks the system clock for the current instant. We can use the truncatedTo() method to round off the value to the nearest second. The second value can then be changed to a string to substitute any undesired characters in the time zone information from the timestamp.
Instant.now() 方法会询问系统时钟当前的瞬时值。我们可以使用 truncatedTo() 方法将数值四舍五入到最接近的秒。然后可以将第二个值更改为字符串,以替代时间戳中时区信息中任何不需要的字符。
3.4. Using LocalDateTime
3.4.使用 LocalDateTime
LocalDateTime represents the date and time of the day without a time zone in the ISO-8601 calendar system:
LocalDateTime 表示 ISO-8601 日历系统中不含时区的日期和时间:
@Test
public void whenUsingLocalDateTime_thenGetCurrentTime() {
String currentTime = LocalDateTime.now().format(DATETIME_FORMATTER);
String fileName = getFileName(currentTime);
assertTrue(verifyFileName(fileName));
}
LocalDateTime.now() method queries the default system clock to provide date-time information. We can then pass a DateTimeFormatter to format the timestamp into a string
LocalDateTime.now()方法会查询默认系统时钟以提供日期时间信息。然后,我们可以通过 DateTimeFormatter 将时间戳格式化为字符串
3.5. Using ZonedDateTime
3.5.使用 ZonedDateTime
ZonedDateTime is an immutable representation of a date-time with a time zone:
ZonedDateTime 是带有时区的日期时间的不变表示:
@Test
public void whenUsingZonedDateTime_thenGetCurrentTime() {
String currentTime = ZonedDateTime
.now(ZoneId.of("Europe/Paris"))
.format(DATETIME_FORMATTER);
String fileName = getFileName(currentTime);
assertTrue(verifyFileName(fileName));
}
A time zone identifier is capable of uniquely identifying specific geographical locations on Earth, for example, “Europe/Paris“. Using this identification, we can obtain the ZoneId, which determines the time zone to use for the conversion from Instant to LocalDateTime.
时区标识符能够唯一标识地球上的特定地理位置,例如”欧洲/巴黎“。利用这一标识,我们可以获得 ZoneId,它决定了从 Instant 转换为 LocalDateTime 时要使用的时区。
ZonedDateTime automatically handles daylight savings time (DST) adjustments throughout the year.
ZonedDateTime 全年自动处理夏令时 (DST) 调整。
3.6. Using OffsetDateTime
3.6.使用 OffsetDateTime
OffsetDateTime is a simplified version of ZonedDateTime that ignores time zones. Time zone offsets vary between different regions of the world. For example, “+2:00” denotes a time in a time zone two hours after UTC. We can alter the default time in UTC by using the offset value with ZoneOffSet:
OffsetDateTime是ZonedDateTime的简化版本,它忽略了时区。世界不同地区的时区偏移各不相同。例如,”+2:00“表示时区时间比 UTC 晚两小时。我们可以使用 ZoneOffSet 中的偏移值来更改 UTC 中的默认时间:
@Test
public void whenUsingOffsetDateTime_thenGetCurrentTime() {
String currentTime = OffsetDateTime
.of(LocalDateTime.now(), ZoneOffset.of("+02:00"))
.format(DATETIME_FORMATTER);
String fileName = getFileName(currentTime);
assertTrue(verifyFileName(fileName));
}
Both ZonedDateTime and OffsetDateTime store an instant of the timeline up to a precision of nanoseconds. Knowing their differences helps us choose between them.
ZonedDateTime和OffsetDateTime都存储时间线的瞬间,精度可达纳秒。了解它们的差异有助于我们在它们之间做出选择。
4. Current Time With Joda-Time
4.使用 Joda-Time 查看当前时间
Joda-Time is a well-known library for date and time processing. It’s one of the most popular libraries among developers as a replacement for troublesome legacy Java classes. It handles date and time values using immutable classes.
Joda-Time 是一个著名的日期和时间处理库。作为麻烦的传统 Java 类的替代库,它是最受开发人员欢迎的库之一。它使用不可变类处理日期和时间值。
Let’s add the Joda-Time Maven dependency in pom.xml:
让我们在 pom.xml 中添加 Joda-Time Maven 依赖关系:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.12.5</version>
</dependency>
4.1. Using Joda DateTime
4.1.使用 Joda DateTime
DateTime.now() method obtains a DateTime set to the current system millisecond time using the default time zone. We can then convert it to a String with a defined timestamp format:
DateTime.now()方法使用默认时区获取设置为当前系统毫秒时间的DateTime。然后,我们可以用定义的时间戳格式将其转换为 String 格式:
@Test
public void whenUsingJodaTime_thenGetCurrentTime() {
String currentTime = DateTime.now().toString(TIMESTAMP_FORMAT);
String fileName = getFileName(currentTime);
assertTrue(verifyFileName(fileName));
}
4.2. Using Joda Instant
4.2.使用 Joda Instant
Joda-Time library also provides the Instant class to capture the moment in the current timeline. We can use DateTimeFormat to transform the timestamp into the desired string pattern:
Joda-Time 库还提供了 Instant 类,用于捕捉当前时间轴中的时刻。我们可以使用 DateTimeFormat 将时间戳转换为所需的字符串模式:
@Test
public void whenUsingJodaTimeInstant_thenGetCurrentTime() {
String currentTime = DateTimeFormat
.forPattern(TIMESTAMP_FORMAT)
.print(org.joda.time.Instant.now().toDateTime());
String fileName = getFileName(currentTime);
assertTrue(verifyFileName(fileName));
}
5. Conclusion
5.结论
In this article, we discovered a variety of methods for obtaining the current timestamp within a Java program and utilized them to generate a filename. We acquired the current timestamp by using various Java DateTime API classes and the Joda-Time library.
在本文中,我们发现了在 Java 程序中获取当前时间戳的多种方法,并利用这些方法生成文件名。我们通过使用各种 Java DateTime API 类和 Joda-Time 库来获取当前时间戳。
As always, the full code for this article can be found over on GitHub.
与往常一样,本文的完整代码可在 GitHub 上找到。