Get Date Without Time in Java – 在Java中获取没有时间的日期

最后修改: 2018年 6月 26日

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

1. Introduction

1.介绍

In this short tutorial, we’ll show how to get a Date without time in Java.

在这个简短的教程中,我们将展示如何在Java中获得一个没有时间的Date

We’ll show how to do this before and after Java 8 since things have become a bit different after the release of the new time API in Java 8.

我们将展示在Java 8之前和之后如何做到这一点,因为在Java 8中新的时间API发布之后,事情变得有些不同。

2. Before Java 8

2.在Java 8之前

Before Java 8, there wasn’t a direct way to get a Date without time unless we were using third party libraries like Joda-time.

在Java 8之前,除非我们使用Joda-time这样的第三方库,否则没有直接的方法来获得不含时间的Date

This is because the Date class in Java is a representation of a specific instant in time, expressed in milliseconds. Therefore, this makes it impossible to ignore the time on a Date.

这是因为Java中的Date类是对特定时间瞬间的表示,以毫秒表示。因此,这使得我们无法忽略Date上的时间。

In the next sections, we’ll show some common workarounds to tackle this problem.

在接下来的章节中,我们将展示一些常见的变通方法来解决这个问题。

2.1. Using Calendar

2.1.使用Calendar

One of the most common ways to get a Date without time is to use the Calendar class to set the time to zero. By doing this we get a clean date, with the time set at the start of the day.

要得到一个没有时间的Date,最常见的方法之一是使用Calendar类将时间设置为零。通过这样做,我们得到一个干净的日期,时间设置在一天的开始。

Let’s see it in code:

让我们看看它的代码。

public static Date getDateWithoutTimeUsingCalendar() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}

If we call this method we get a date like this:

如果我们调用这个方法,就会得到一个这样的日期。

Sat Jun 23 00:00:00 CEST 2018

As we can see, it returns a full date with the time set to zero, but we can’t ignore the time.

我们可以看到,它返回一个完整的日期,时间设置为零,但我们不能忽略时间

Also, to make sure that there is no time set in the Date returned, we can create the following test:

另外,为了确保返回的Date中没有设置时间,我们可以创建以下测试。

@Test
public void whenGettingDateWithoutTimeUsingCalendar_thenReturnDateWithoutTime() {
    Date dateWithoutTime = DateWithoutTime.getDateWithoutTimeUsingCalendar();

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateWithoutTime);
    int day = calendar.get(Calendar.DAY_OF_MONTH);

    calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY - 1);
    assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH));

    calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY);
    assertNotEquals(day, calendar.get(Calendar.DAY_OF_MONTH));
}

As we can see, when we add to the date the milliseconds of a day minus one we still get the same day, but when we add a full day we get the next day.

正如我们所看到的,当我们把一天的毫秒数加上去时,我们仍然得到同一天,但当我们加上一整天时,我们得到的是第二天的日期。

2.2. Using a Formatter

2.2.使用格式化器

Another way to do this is by formatting a Date into a String without the time and then convert that String back to a Date. Since the String was formatted without the time the Date converted will have the time set to zero.

另一种方法是:Date格式化为不带时间的String,然后将String转换回Date。由于String的格式化不含时间,转换后的Date的时间将被设置为零。

Let’s implement it to see how it works:

让我们来实施它,看看它是如何工作的。

public static Date getDateWithoutTimeUsingFormat() 
  throws ParseException {
    SimpleDateFormat formatter = new SimpleDateFormat(
      "dd/MM/yyyy");
    return formatter.parse(formatter.format(new Date()));
}

This implementation returns the same as the method shown in the previous section:

这个实现的结果与上一节所示的方法相同。

Sat Jun 23 00:00:00 CEST 2018

Again, we can use a test like we did before to make sure there is no time in the Date returned.

同样,我们可以像之前那样使用一个测试来确保返回的Date中没有时间。

3. Using Java 8

3.使用Java 8

With the release of the new time API in Java 8, there is an easier way to get a date without the time. One of the new features that this new API has brought is that there are several classes to work with dates with or without time, or even to work only with time.

随着Java 8中新的时间API的发布,有了一种更简单的方法来获得一个没有时间的日期。这个新的API带来的一个新特性是,有几个类可以处理有时间或无时间的日期,甚至可以只处理时间。

For the sake of this article, we’ll focus on the class LocalDate, which represents exactly what we need, a date without the time.

在这篇文章中,我们将专注于LocalDate类,它正好代表了我们需要的东西,一个没有时间的日期。

Let’s see it with this example:

让我们通过这个例子来看看。

public static LocalDate getLocalDate() {
    return LocalDate.now();
}

This method returns a LocalDate object with this date representation:

该方法返回一个具有该日期表示的LocalDate对象。

2018-06-23

As we can see, it returns just a date, the time is completely ignored.

我们可以看到,它只返回一个日期,时间被完全忽略了

Again, let’s test it as before to make sure that this method works as expected:

再一次,让我们像以前一样进行测试,以确保这个方法像预期的那样工作。

@Test
public void whenGettingLocalDate_thenReturnDateWithoutTime() {
    LocalDate localDate = DateWithoutTime.getLocalDate();

    long millisLocalDate = localDate
      .atStartOfDay()
      .toInstant(OffsetDateTime
        .now()
        .getOffset())
      .toEpochMilli();

    Calendar calendar = Calendar.getInstance();

    calendar.setTimeInMillis(
      millisLocalDate + MILLISECONDS_PER_DAY - 1);
    assertEquals(
      localDate.getDayOfMonth(), 
      calendar.get(Calendar.DAY_OF_MONTH));

    calendar.setTimeInMillis(millisLocalDate + MILLISECONDS_PER_DAY);
    assertNotEquals(
      localDate.getDayOfMonth(), 
      calendar.get(Calendar.DAY_OF_MONTH));
}

4. Conclusion

4.结论

In this article, we’ve shown how to get a Date without time in Java. We first showed how to do it prior to Java 8 and also using Java 8.

在这篇文章中,我们展示了如何在Java中获得一个没有时间的Date。我们首先展示了在Java 8之前以及使用Java 8时如何做到这一点。

As we could see in the examples implemented in the article, using Java 8 should be always the preferred option, since it has a specific representation to work with dates without time.

正如我们在文章中实施的例子中所看到的,使用Java 8应该永远是首选,因为它有一个特定的表示方法来处理没有时间的日期。

As always, the full source code of the examples is available over on GitHub.

一如既往,这些示例的完整源代码可在GitHub上获得