LocalDate
ThreeTen
Java
DateManipulation
ProgrammingTips

Get first and last day of month using threeten, LocalDate

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Java, working with dates and times has become more structured and intuitive with the introduction of the java.time package in Java 8, also known as JSR-310 or "ThreeTen" (named after its Java Specification Request number). This package provides the LocalDate class, which is central to handling date manipulations without time-zone considerations. In this article, we will delve into how you can obtain the first and last days of a month using LocalDate.

Understanding LocalDate

LocalDate is a class that represents a date without time-zone and time information. It can be used for, among other things, budgeting monthly tasks, timesheets, and creating simple calendar applications. Central to our discussion today will be its ability to elegantly manipulate date information.

Essential Methods

Here are some essential methods provided by the LocalDate class that we'll use and are worth familiarizing:

  • now(): Obtains the current date from the system clock.
  • of(): Creates an instance of LocalDate for a specific date.
  • withDayOfMonth(int dayOfMonth): Returns a copy of the LocalDate with the specified day of the month.
  • lengthOfMonth(): Returns the length of the month represented by the LocalDate, which can change depending on leap years.

Getting the First and Last Day of the Month

The primary task is to determine the first and last days of a given month using LocalDate. We accomplish this task utilizing fluid methods available in the LocalDate API.

Example - Current Month

Below is a step-by-step implementation to find the first and last day of the current month:

java
1import java.time.LocalDate;
2
3public class FirstAndLastDayOfMonth {
4    public static void main(String[] args) {
5        // Getting the current date
6        LocalDate currentDate = LocalDate.now();
7        
8        // Obtaining the first day of the current month
9        LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1);
10        
11        // Obtaining the last day of the current month
12        LocalDate lastDayOfMonth = currentDate.withDayOfMonth(currentDate.lengthOfMonth());
13        
14        // Results
15        System.out.println("First Day of the Month: " + firstDayOfMonth);
16        System.out.println("Last Day of the Month: " + lastDayOfMonth);
17    }
18}

Example - Specific Month and Year

Sometimes, you may want to find the first and last days of a particular month-year combination:

java
1import java.time.LocalDate;
2
3public class SpecificMonth {
4    public static void main(String[] args) {
5        // Specifying a year and month
6        int year = 2023;
7        int month = 5;
8        
9        // Obtaining the first and last day of the specified month
10        LocalDate firstDayOfMonth = LocalDate.of(year, month, 1);
11        LocalDate lastDayOfMonth = firstDayOfMonth.withDayOfMonth(firstDayOfMonth.lengthOfMonth());
12        
13        // Results
14        System.out.println("First Day of the Month: " + firstDayOfMonth);
15        System.out.println("Last Day of the Month: " + lastDayOfMonth);
16    }
17}

Special Considerations

Leap Years

The LocalDate class automatically takes leap years into account. If you specify February in a leap year (like 2024), lengthOfMonth() will correctly return 29.

Validating Dates

It ensures that inputs like month and day combinations are valid. Trying to create an invalid date will throw a DateTimeException.

java
1try {
2    LocalDate invalidDate = LocalDate.of(2023, 2, 29); // Exception in non-leap year
3} catch (DateTimeException e) {
4    System.out.println("Caught Exception: " + e.getMessage());
5}

Table of Key Methods

MethodDescription
now()Obtains current date from the system clock.
of(year, month, dayOfMonth)Creates an instance of LocalDate for a specific date.
withDayOfMonth(day)Replaces the day of the month in the LocalDate instance to a specified value.
lengthOfMonth()Returns the number of days in the month. Takes leap years into account when applicable.

Conclusion

The java.time.LocalDate class offers a simple yet powerful way to handle dates in Java. By leveraging its methods, obtaining the first and last days of a month—whether it's the current month or a specified month—is not only straightforward but also reliable. This approach abstracts much of the traditional complexity encountered with date manipulation, making it a preferred choice for contemporary Java applications.


Course illustration
Course illustration

All Rights Reserved.