Add Hours To a Date In Java – 在Java中为日期添加小时数

最后修改: 2018年 7月 15日

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

1. Overview

1.概述

Before Java 8, java.util.Date was one of the most commonly used classes for representing date-time values in Java.

在Java 8之前,java.util.Date是Java中最常用的表示日期时间值的类之一。

Then Java 8 introduced java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 also allows us to represent a specific time on the timeline using java.time.Instant.

然后Java 8引入了java.time.LocalDateTimejava.time.ZonedDateTime。Java 8还允许我们使用java.time.Instant.DateTime来表示时间线上的一个特定时间。

In this tutorial, we’ll learn to add or subtract n hours from a given date-time in Java. We’ll first look at some standard Java date-time related classes, and then we’ll showcase a few third-party options.

在本教程中,我们将学习在Java中从一个给定的日期时间中添加或减去n小时的方法。我们将首先看看一些标准的Java日期时间相关的类,然后我们将展示一些第三方的选择。

To learn more about the Java 8 DateTime API, we would suggest reading this article.

要了解有关 Java 8 DateTime API 的更多信息,我们建议阅读这篇文章

2. java.util.Date

2、java.util.Date

If we’re using Java 7 or lower, we can use the java.util.Date and java.util.Calendar classes for most date-time related handling.

如果我们使用Java 7或更低版本,我们可以使用java.util.Datejava.util.Calendar类来处理大多数与日期时间有关的事务。

Let’s see how to add n hours to a given Date object:

让我们看看如何将n小时添加到一个给定的Date对象中。

public Date addHoursToJavaUtilDate(Date date, int hours) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.HOUR_OF_DAY, hours);
    return calendar.getTime();
}

Note that Calendar.HOUR_OF_DAY is referring to a 24-hour clock.

请注意,Calendar.HOUR_OF_DAY是指24小时的时钟

The above method returns a new Date object, the value of which would be either (date + hours) or (date – hours), depending on whether we pass a positive or negative value of hours respectively.

上述方法返回一个新的Date对象,其值将是(date + hours)(date – hours),这取决于我们传递的hours的值是正还是负。

Suppose we have a Java 8 application, but still we want to work our way with java.util.Date instances.

假设我们有一个Java 8应用程序,但我们仍然想用java.util.Date实例的方式工作。

For such a case, we can opt to take the following alternate approach:

对于这种情况,我们可以选择采取以下替代方法。

  1. Use java.util.Date toInstant() method to convert a Date object to a java.time.Instant instance
  2. Add a specific Duration to the java.time.Instant object using the plus() method
  3. Recover our java.util.Date instance by passing in the java.time.Instant object to the java.util.Date.from() method

Let’s have a quick look at this approach:

让我们快速了解一下这种方法。

@Test
public void givenJavaUtilDate_whenUsingToInstant_thenAddHours() {
    Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0)
      .getTime();
    Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0)
      .getTime();

    assertThat(Date.from(actualDate.toInstant().plus(Duration.ofHours(2))))
      .isEqualTo(expectedDate);
}

However, note that it’s always recommended to use the new DateTime API for all applications on Java 8 or higher versions.

然而,请注意,始终建议在Java 8或更高版本的所有应用程序中使用新的DateTime API。

3. java.time.LocalDateTime/ZonedDateTime

3.java.time.LocalDateTime/ZonedDateTime

In Java 8 or later, adding hours to either a java.time.LocalDateTime or java.time.ZonedDateTime instance is pretty straightforward and makes use of the plusHours() method:

在 Java 8 或更高版本中,向 java.time.LocalDateTimejava.time.ZonedDateTime 实例添加小时是非常简单的,并且使用了 plusHours() 方法。

@Test
public void givenLocalDateTime_whenUsingPlusHours_thenAddHours() {
    LocalDateTime actualDateTime = LocalDateTime
      .of(2018, Month.JUNE, 25, 5, 0);
    LocalDateTime expectedDateTime = LocalDateTime.
      of(2018, Month.JUNE, 25, 10, 0);

    assertThat(actualDateTime.plusHours(5)).isEqualTo(expectedDateTime);
}

What if we wish to subtract a few hours?

如果我们希望减去几个小时呢?

Passing a negative value of hours to plusHours() method would do just fine. However, it’s recommended to use the minusHours() method:

plusHours()方法传递一个负的小时值就可以了。然而,建议使用minusHours()方法。

@Test
public void givenLocalDateTime_whenUsingMinusHours_thenSubtractHours() {
    LocalDateTime actualDateTime = LocalDateTime
      .of(2018, Month.JUNE, 25, 5, 0);
    LocalDateTime expectedDateTime = LocalDateTime
      .of(2018, Month.JUNE, 25, 3, 0);
   
    assertThat(actualDateTime.minusHours(2)).isEqualTo(expectedDateTime);

}

The plusHours() and minusHours() methods in the java.time.ZonedDateTime works exactly the same way.

java.time.ZonedDateTime中的plusHours()minusHours()方法的工作方式完全相同。

4. java.time.Instant

4.java.time.instant

As we know, java.time.Instant introduced in Java 8 DateTime API represents a specific moment on the timeline.

我们知道,java.time.Instant 在Java 8 DateTime API中引入,表示时间线上的一个特定时刻。

To add some hours to an Instant object, we can use its plus() method with a java.time.temporal.TemporalAmount:

为了给Instant对象增加一些时间,我们可以使用它的 plus()方法,并使用java.time.temporal.TemporalAmount

@Test
public void givenInstant_whenUsingAddHoursToInstant_thenAddHours() {
    Instant actualValue = Instant.parse("2018-06-25T05:12:35Z");
    Instant expectedValue = Instant.parse("2018-06-25T07:12:35Z");

    assertThat(actualValue.plus(2, ChronoUnit.HOURS))
      .isEqualTo(expectedValue);
}

Similarly, the minus() method can be used for subtracting a specific TemporalAmount.

类似地, minus()方法可用于减去一个特定的TemporalAmount

5. Apache Commons DateUtils

5.Apache Commons的DateUtils

The DateUtils class from the Apache Commons Lang library exposes a static addHours() method:

Apache Commons Lang库中的DateUtils类暴露了一个staticaddHours()方法。

public static Date addHours(Date date, int amount)

The method takes-in a java.util.Date object along with an amount we wish to add to it, the value of which could be either positive or negative.

该方法接收一个 java.util.Date对象,以及我们希望添加到它的金额,其值可以是正数或负数。

A new java.util.Date object is returned as an outcome:

一个新的 java.util.Date对象作为结果被返回。

@Test
public void givenJavaUtilDate_whenUsingApacheCommons_thenAddHours() {
    Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0)
      .getTime();
    Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0)
      .getTime();

    assertThat(DateUtils.addHours(actualDate, 2)).isEqualTo(expectedDate);
}

The latest version of Apache Commons Lang is available at Maven Central.

最新版本的Apache Commons Lang可在Maven Central.获得。

6. Joda Time

6.乔达时间

Joda Time is an alternative to the Java 8 DateTime API and provides its own DateTime implementations.

Joda Time是Java 8 DateTime API的替代品,它提供了自己的DateTime实现。

Most of its DateTime related classes expose plusHours() and minusHours() methods to help us add or subtract a given number of hours from a DateTime object.

它的大多数DateTime相关类都暴露了 plusHours()minusHours()方法,以帮助我们从DateTime对象中添加或减去指定的小时数。

Let’s look at an example:

我们来看看一个例子。

@Test
public void givenJodaDateTime_whenUsingPlusHoursToDateTime_thenAddHours() {
    DateTime actualDateTime = new DateTime(2018, 5, 25, 5, 0);
    DateTime expectedDateTime = new DateTime(2018, 5, 25, 7, 0);

    assertThat(actualDateTime.plusHours(2)).isEqualTo(expectedDateTime);
}

We can easily check the latest available version of Joda Time at Maven Central.

我们可以在Maven Central上轻松查看Joda Time的最新可用版本。

7. Conclusion

7.结语

In this tutorial, we covered several ways to add or subtract a given number of hours from standard Java date-time values.

在本教程中,我们介绍了从标准Java日期时间值中加减给定小时数的几种方法。

We also looked at some third-party libraries as an alternative. As usual, the complete source code is available over on GitHub.

我们还研究了一些第三方库作为替代。像往常一样,完整的源代码可以在GitHub上找到。