Get First Date of Current Month in Java – 用 Java 获取当前月份的第一天

最后修改: 2023年 11月 5日

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

1. Overview

1.概述

In this short article, we’ll highlight how to get the first date of the current month in Java.

在这篇短文中,我们将重点介绍如何用 Java 获取当前月份的第一个日期。

First, we’re going to elucidate how to do it using JDK solutions. Then, we will showcase how to achieve the same outcome using third-party libraries such as Joda Time.

首先,我们将阐明如何使用 JDK 解决方案来实现这一目标。然后,我们将展示如何使用第三方库(如 Joda Time)实现同样的结果。

2. Introduction to the Problem

2.问题介绍

As always, let’s understand the main problem through an example. Let’s assume that our current date is 2023-10-15:

和往常一样,让我们通过一个例子来了解主要问题。假设当前日期是 2023-10-15:

LocalDate currentDate = LocalDate.of(2023, 10, 15);

Here, we aim to get the first date of October which is 2023-10-01. So, let’s dive into the code.

在这里,我们的目标是获取十月的第一个日期,即 2023-10-01。那么,让我们进入代码。

3. Using the Calendar Class

3.使用 Calendar

The Calendar class provides a set of handy methods that we can use to manipulate dates and times. It offers a convenient way to get the first date of a given month.

Calendar 类提供了一系列方便的方法,我们可以用它们来操作日期和时间。它提供了一种方便的方法来获取给定月份的第一个日期。

So, let’s see it in action:

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

@Test
void givenMonth_whenUsingCalendar_thenReturnFirstDay() {
    Date currentDate = new GregorianCalendar(2023, Calendar.NOVEMBER, 23).getTime();
    Date expectedDate = new GregorianCalendar(2023, Calendar.NOVEMBER, 1).getTime();

    Calendar cal = Calendar.getInstance();
    cal.setTime(currentDate);
    cal.set(Calendar.DAY_OF_MONTH, 1);

    assertEquals(expectedDate, cal.getTime());
}

As we can see, we alter the calendar time to the given date. Then, we call set(Calendar.DAY_OF_MONTH, 1) to set the day of the current month to 1.

正如我们所看到的,我们将日历时间更改为给定的日期。然后,我们调用 set(Calendar.DAY_OF_MONTH, 1) 将当前月份的天数设置为 1

Furthermore, we return the new date, which denotes the first date of the month using the getTime() method.

此外,我们还将使用 getTime() 方法返回新日期,即本月的第一个日期。

4. Using the Java 8 Date Time API

4.使用 Java 8 日期时间 API

Java 8 comes with a host of ready-to-use features such as the date time API. This new API was introduced to address the drawbacks of the older API based on the Calendar class.

Java 8 提供了大量随时可用的功能,例如 日期时间 API。引入这个新的 API 是为了解决基于 Calendar 类的旧 API 的缺点。

Please note that this new Java 8 API is the best way to go when it comes to working with dates.

请注意,新的 Java 8 API 是处理日期的最佳方式。

So, let’s go down the rabbit hole and see what methods this new API offers to answer our central question.

那么,让我们进入兔子洞,看看这个新的应用程序接口提供了哪些方法来回答我们的核心问题。

4.1. Using the LocalDate Class

4.1.使用 LocalDate 类

LocalDate is a great option to consider if we want to get the first day of the current month. This class provides the withDayOfMonth() method that we can use to return a new date with the day altered.

LocalDate 是一个很好的选择,如果我们想获得当前月份的第一天的话。该类提供了withDayOfMonth() 方法,我们可以使用该方法返回更改了日期的新日期

So, let’s see in practice:

那么,让我们在实践中看看吧:

@Test
void givenMonth_whenUsingLocalDate_thenReturnFirstDay() {
    LocalDate currentDate = LocalDate.of(2023, 9, 6);
    LocalDate expectedDate = LocalDate.of(2023, 9, 1);

    assertEquals(expectedDate, currentDate.withDayOfMonth(1));
}

As shown above, we used withDayOfMonth(1) to set the day of the specified date to the value 1. That way, we get the first date of the month.

如上图所示,我们使用 withDayOfMonth(1) 将指定日期的日设置为值 1。这样,我们就得到了该月的第一个日期。

4.2. Using the TemporalAdjusters Class

4.2.使用TemporalAdjusters

Similarly, we can use TemporalAdjusters to tackle our challenge. As the name implies, this class represents several adjusters that aim to modify temporal objects such as days, and months.

同样,我们可以使用 TemporalAdjusters 来应对我们的挑战。顾名思义,该类表示多个调整器,旨在修改时间对象(如日和月)

Among these adjusters, we find firstDayOfMonth. Next, let’s add a new test case to test our adjuster:

在这些调整器中,我们找到了 firstDayOfMonth。接下来,让我们添加一个新的测试用例来测试我们的调整器:

@Test
void givenMonth_whenUsingTemporalAdjusters_thenReturnFirstDay() {
    LocalDate currentDate = LocalDate.of(2023, 7, 19);
    LocalDate expectedDate = LocalDate.of(2023, 7, 1);

    assertEquals(expectedDate, currentDate.with(TemporalAdjusters.firstDayOfMonth()));
}

Typically, firstDayOfMonth returns the first day of a particular month. Please note that we used the with() method to get the new adjusted copy of the date.

通常,firstDayOfMonth 返回特定月份的第一天。请注意,我们使用了 with() 方法来获取日期的新调整副本。

4.3. Using the YearMonth Class

4.3.使用 YearMonth 类

YearMonth introduced the atDay() method to combine a specific year/month with the day passed as a parameter.

YearMonth引入了atDay()方法,将特定的年/月与作为参数传递的日期结合起来。

Now, let’s see how to use this method to achieve our objective:

现在,让我们看看如何使用这种方法来实现我们的目标:

@Test
void givenMonth_whenUsingYearMonth_thenReturnFirstDay() {
    YearMonth currentDate = YearMonth.of(2023, 4);
    LocalDate expectedDate = LocalDate.of(2023, 4, 1);

    assertEquals(expectedDate, currentDate.atDay(1));
}

Here, we specified 1 as the parameter to denote the first day of the given year and month.

在这里,我们指定 1 作为参数,表示给定年月的第一天

5. Using the Joda Time Library

5.使用 Joda 时间库

Another solution would be using the Joda Time library. It provides a standard API for date-time manipulation before Java 8.

另一种解决方案是使用 Joda 时间库。它为 Java 8 之前的日期时间操作提供了标准 API。

Before starting working with this library, we need first to add its dependency to the pom.xml file:

在开始使用该库之前,我们首先需要将其 依赖关系添加到 pom.xml 文件中:

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

Joda Time comes with a variant of the LocalDate class to represent a date. So, let’s exemplify the use of this class with a new test case:

Joda Time 附带了一个 LocalDate 类的变体来表示日期。因此,让我们用一个新的测试用例来示范该类的使用:

@Test
void givenMonth_whenUsingJodaTime_thenReturnFirstDay() {
    org.joda.time.LocalDate currentDate = org.joda.time.LocalDate.parse("2023-5-10");
    org.joda.time.LocalDate expectedDate = org.joda.time.LocalDate.parse("2023-5-1");

    assertEquals(expectedDate, currentDate.dayOfMonth()
      .withMinimumValue());
}

As the name indicates, dayOfMonth() allows retrieving the day of the given month. Furthermore, we used the withMinimumValue() method to set the day of the returned date to the minimum value which is 1.

正如其名称所示,dayOfMonth() 允许检索给定月份的日期。此外,我们使用 withMinimumValue() 方法将返回日期的日设置为最小值,即 1。

6. Conclusion

6.结论

In this short tutorial, we explored different ways of getting the first day of the current month in Java.

在这个简短的教程中,我们探讨了用 Java 获取当前月份第一天的不同方法。

First, we discussed how to do it using JDK classes. Then, we illustrated how to accomplish the same objective using Joda Time API.

首先,我们讨论了如何使用 JDK 类来实现这一目标。然后,我们说明了如何使用 Joda Time API 实现同样的目标。

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

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