Convert Date to Unix Timestamp in Java – 用 Java 将日期转换为 Unix 时间戳

最后修改: 2024年 2月 9日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In computer science, Unix timestamp, also known as epoch time, is a standard way to represent a particular point in time. It denotes the number of seconds that have elapsed since January 1, 1970.

在计算机科学中,Unix 时间戳也称为 epoch 时间,是表示特定时间点的标准方法。它表示自 1970 年 1 月 1 日以来已过去的秒数。

In this tutorial, we’ll shed light on how to convert a classic date into a Unix timestamp. First, we’ll explore how to do this using built-in JDK methods. Then, we’ll illustrate how to achieve the same objective using external libraries such as Joda-Time.

在本教程中,我们将介绍如何将经典日期转换为 Unix 时间戳。首先,我们将探讨如何使用 JDK 内置方法来实现这一目标。然后,我们将说明如何使用 Joda-Time 等外部库实现相同的目标。

2. Using the Java 8+ Date-Time API

2.使用 Java 8+ 日期-时间 API

Java 8 introduced a new Date-Time API that we can use to answer our central question. This new API comes with several methods and classes to manipulate dates. So, let’s take a close look at each option.

Java 8 引入了新的日期时间 API,我们可以使用它来回答我们的中心问题。这个新的 API 提供了多个用于操作日期的方法和类。因此,让我们仔细研究一下每个选项。

2.1. Using the Instant Class

2.1.使用 Instant

In short, the Instant class models an instantaneous point on the timeline. This class provides a straightforward and concise method to get the Unix time from a given date.

简而言之,Instant 类模拟了时间轴上的瞬时点。该类提供了从给定日期获取 Unix 时间的简洁明了的方法

So, let’s see it in action:

那么,让我们来看看它的实际效果吧:

@Test
void givenDate_whenUsingInstantClass_thenConvertToUnixTimeStamp() {
    Instant givenDate = Instant.parse("2020-09-08T12:16:40Z");

    assertEquals(1599567400L, givenDate.getEpochSecond());
}

As we can see, the Instant class offers the getEpochSecond() method to get the epoch timestamp in seconds from the specified date.

正如我们所见,Instant 类提供了getEpochSecond()方法,用于从指定日期开始获取以秒为单位的纪元时间戳。

2.2. Using LocalDateTime Class

2.2.使用 LocalDateTime

LocalDateTime is another option to consider when converting a date to epoch time. This class denotes a combination of date and time, often viewed as year, month, day, hour, minute, and second.

LocalDateTime 是将日期转换为纪元时间时需要考虑的另一个选项。该类表示日期和时间的组合,通常被视为年、月、日、时、分和秒。

Typically, this class provides the toEpochSecond() method to get the epoch time in seconds from the specified date time:

通常情况下,该类提供 toEpochSecond() 方法,用于从指定的日期时间获取以秒为单位的纪元时间

@Test
void givenDate_whenUsingLocalDateTimeClass_thenConvertToUnixTimeStamp() {
    LocalDateTime givenDate = LocalDateTime.of(2023, 10, 19, 22, 45);

    assertEquals(1697755500L, givenDate.toEpochSecond(ZoneOffset.UTC));
}

As shown above, unlike other methods, toEpochSecond() accepts a ZoneOffset object, which allows us to define the fixed offset of the timezone, UTC.

如上所示,与其他方法不同,toEpochSecond() 接受一个 ZoneOffset 对象,该对象允许我们定义时区 UTC 的固定偏移。

3. Using the Legacy Date API

3.使用传统日期 API

Alternatively, we can use Date and Calendar classes from the old API to achieve the same outcome. So, let’s go down the rabbit hole and see how to use them in practice.

或者,我们可以使用旧 API 中的 DateCalendar 类来实现相同的结果。因此,让我们进入兔子洞,看看如何在实践中使用它们。

3.1. Using the Date Class

3.1.使用 Date

In Java, the Date class represents a specific point in time with millisecond precision. It provides one of the easiest ways to convert a date into a Unix timestamp through the getTime() method:

在 Java 中,Date 类以毫秒精度表示特定的时间点。通过 getTime() 方法,它提供了将日期转换为 Unix 时间戳的最简单方法之一

@Test
void givenDate_whenUsingDateClass_thenConvertToUnixTimeStamp() throws ParseException {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date givenDate = dateFormat.parse("2023-10-15 22:00:00");

    assertEquals(1697407200L, givenDate.getTime() / 1000);
}

Typically, the method returns the number of milliseconds since the epoch of the passed date. As we can see, we divided the result by 1000 to get the epoch in seconds. However, this class is considered outdated and shouldn’t be used when working with dates.

通常情况下,该方法会返回自传递日期的纪元起的毫秒数。正如我们所看到的,我们将结果除以 1000,得到了以秒为单位的纪元。然而,这个类已经过时,在处理日期时不应使用

3.2. Using the Calendar Class

3.2.使用 Calendar

Similarly, we can use the Calendar class from the same package, java.util. This class provides a host of methods to set and manipulate dates.

同样,我们可以使用同一软件包 java.util 中的 Calendar 类。该类提供了大量设置和操作日期的方法。

With Calendar, we have to call getTimeInMillis() to return the Unix time from the specified date:

使用 Calendar 时,我们必须调用 getTimeInMillis() 返回指定日期的 Unix 时间

@Test
void givenDate_whenUsingCalendarClass_thenConvertToUnixTimeStamp() throws ParseException {
    Calendar calendar = new GregorianCalendar(2023, Calendar.OCTOBER, 17);
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));

    assertEquals(1697500800L, calendar.getTimeInMillis() / 1000);
}

Please note that this method, as the name implies, returns the timestamp in milliseconds. The drawback of this choice is that Calendar is declared a de facto legacy since it belongs to the old API.

请注意,顾名思义,该方法以毫秒为单位返回时间戳。这种选择的缺点是,Calendar 被宣布为事实上的遗产,因为它属于旧的 API

4. Using Joda-Time

4.使用 Joda-Time

Another solution would be using the Joda-Time library. Before starting working with the library, let’s add its dependency to pom.xml:

另一种解决方案是使用 Joda-Time 库。在开始使用该库之前,我们先将其 依赖关系添加到 pom.xml 中:

<dependency>
    <groupId>joda-time</groupId> 
    <artifactId>joda-time</artifactId> 
    <version>2.12.6</version> 
</dependency>

Joda-Time offers its version of the Instant class that we can use to tackle our challenge. So, let’s illustrate how to use this class using a new test case:

Joda-Time提供了其版本的Instant类,我们可以用它来应对我们的挑战。因此,让我们使用一个新的测试用例来说明如何使用该类:

@Test
void givenDate_whenUsingJodaTimeInstantClass_thenConvertToUnixTimeStamp() {
    org.joda.time.Instant givenDate = org.joda.time.Instant.parse("2020-09-08T12:16:40Z");

    assertEquals(1599567400L, givenDate.getMillis() / 1000);
}

As illustrated, the Instant class provides a direct way to get the number of milliseconds since the epoch.

如图所示,Instant 类提供了一种直接获取自纪元开始的毫秒数的方法。

DateTime class is another solution to consider when working with Joda-Time. It offers the getMillis() method to return the number of milliseconds passed since the epoch of the DateTime instant:

DateTime 类是使用 Joda-Time 时可考虑的另一种解决方案。它提供了 getMillis() 方法,用于返回自DateTime瞬时的纪元以来所经过的毫秒数:

@Test
void givenDate_whenUsingJodaTimeDateTimeClass_thenConvertToUnixTimeStamp() {
    DateTime givenDate = new DateTime("2020-09-08T12:16:40Z");

    assertEquals(1599567400L, givenDate.getMillis() / 1000);
}

Unsurprisingly, the test case passed with success.

不出所料,测试用例成功通过。

5. Conclusion

5.结论

In this short article, we explored different ways of converting a given date into a Unix timestamp.

在这篇短文中,我们探讨了将给定日期转换为 Unix 时间戳的不同方法。

First, we explained how to do this using core JDK methods and classes. Then, we showcased how to achieve the same objective using Joda-Time.

首先,我们解释了如何使用 JDK 核心方法和类实现这一目标。然后,我们展示了如何使用 Joda-Time 实现同样的目标。

As always, the code used in this article can be found over on GitHub.

与往常一样,本文中使用的代码可以在 GitHub 上找到