SoFunction
Updated on 2025-03-08

Explanation of detailed usage of the Date LocalDate class in JAVA

Preface

It is one of the date classes introduced by Java 8, located inIn the package, it provides a simple way to represent dates, excluding time and time zone information. Let me explain his various uses.

Usage 1: Get some information about the current date:

LocalDateA date that represents a year, month and date, and its general form is: yyyy-MM-dd. For example: 2023-10-11.LocalDate is modified by final in JAVA.is immutable and once created, its value cannot be changed. If you need to modify the date, you can create a new oneLocalDateObject.

1. Get the current date: You can use () to get the current date.

LocalDate currentDate = ();//Create a LocalData object to get the current date("The current date is:"+currentDate);

The output result is:

The current date is: 2023-10-11

2. In addition to obtaining the entire date, you can also obtain basic information such as the current year, month, and day.

// Get the current dateLocalDate currentDate = ();
// Get the yearint year = ();
// Get monthMonth month = ();
// Getting Dayint day = ();
("Year: " + year);
("Month: " + month);
("day: " + day);

The output result is:(If you want to get a month int form you can use: int monthValue = ();)

Year: 2023
Month: OCTOBER
Day: 11

3. Get the day of the week, get the day of the date in the year, get the number of days in the month where the date is, get the number of days in the year where the date is, and check whether the year where the date is a leap year.

LocalDate currentDate = ();
// Get the enumeration value of the day of the weekDayOfWeek dayOfWeek = ();
// Get what day of the yearint dayOfYear = ();
// Check whether the year where the date is located is a leap yearboolean isLeapYear = ();
// Get the number of days in the month when the date isint daysInMonth = ();
// Get the number of days in the year the date isint daysInYear = ();
// Get the integer value of the day of the weekint dayOfWeekValue = ().getValue();
("Current date: " + currentDate);             //Current date: 2023-10-11("Today is the week" + dayOfWeekValue);         //Today is 3 weeks("What day of the week: " + dayOfWeek);                //What day of the week: WEDNESDAY("What day of the date in the year: " + dayOfYear);    //What day of the date in the year: 284("Is it a leap year?" + isLeapYear);           //Is it a leap year: false("The number of days in the current month: " + daysInMonth);      //The number of days in the current month: 31("Number of days in the current year: " + daysInYear);       //The number of days in the current year: 365

Usage 2: Create a specific date:

Available(year, month, day)To create a specific date object

LocalDate currentDate1 = (2023,10,22);
("The current date is:"+currentDate1);

The output result is:

The current date is: 2023-10-22

In addition to using   to create a specific date object, we can also convert a standard String object into a LocalData object:  ,Used to parse the date represented by a string intoLocalDateObject. It allows you to convert string dates into date objects in the specified date format for subsequent operations or display.

//Create a string dateString stringdata="2023-01-06";
//Format date rulesDateTimeFormatter formatter = ("yyyy-MM-dd");
//Convert string date to LocalDate object according to the rulesLocalDate stringcurrentDate1= (stringdata,formatter);
("The current date is:"+stringcurrentDate1);

The output result is: (It should be noted that the date format you stipulate should be: yyyy-MM-dd. You cannot write 2023-1-06, otherwise an exception will be thrown)

The current date is: 2023-01-06

Scenarios where string dates are converted into LocalData objects are mostly used to read dates in files. When doing business, dates are often read from data such as Excel, Word, or image recognition invoices, etc. Sometimes these dates are not in standard form, so how to solve it? If the date passed now is: 2023-1-6, how do we convert it into a LocalData object? The answer is to use our DateTimeFormatter formatter, format the date, just set the value to yyyy-M-d to read, and can also make up zeros if needed.

// Original date stringString originalDate = "2023-1-1";
// Parses the date string into a LocalDate objectLocalDate date = (originalDate, ("yyyy-M-d"));
("Date before formatting:" + originalDate);
// Use DateTimeFormatter to format the date, specifying that the width of the month and date parts is two digitsString formattedDate = (("yyyy-MM-dd"));
("Formatted date:" + formattedDate);

The output result is:

Date before formatting: 2023-1-1
Formatted date: 2023-01-01

Usage 3: LocalDate date operation (increase or decrease the specified year, month, day and week)

(long years), minusYears(long years): Increase or decrease the number of years specified.

LocalDate date = ();
LocalDate futureDate = (2); // Add 2 yearsLocalDate pastDate = (1); // Reduce by 1 year("The number of years after the increase:"+futureDate);//The number of years after the increase: 2025-10-11("Reduced years:"+pastDate);//The number of years after reduction:2022-10-11

(long months), minusMonths(long months): Increase or decrease the number of months specified.

(long weeks), minusWeeks(long weeks): Increase or decrease the number of weeks specified.

(long days), minusDays(long days): Increase or decrease the number of days specified. (The function form is the same, so the moon and the sky will not be displayed in code)

5. In addition to operating separately on year, month and Sunday, we can also perform unified operations, such as adding one year and three months (plus is an increase, minus is an decrease)

LocalDate date = ();
LocalDate futureDate = ((1, 2, 0)); // Add 1 year and 3 months("Current date:"+date);       //Current date: 2023-10-11("Addate date:"+futureDate);//Added date:2024-12-11

Usage 4: Get the specific time of the week, month, etc. of the current time

1. Get the first and last day of the week where the current time is:

LocalDate currentDate = ();
// Get the first day of the current week (Monday)LocalDate firstDayOfWeek = (());
// Get the last day of the current week (Sunday)LocalDate lastDayOfWeek = (());
("The first day of the week: " + firstDayOfWeek); //The first day of the week: 2023-10-09("The last day of the week: " + lastDayOfWeek);//The last day of the week: 2023-10-15

2. Get the first and last day of the month where the current time is:

// Get the current dateLocalDate currentDate = ();
// Get the first day of the current monthLocalDate firstDayOfMonth = (());
// Get the last day of the current monthLocalDate lastDayOfMonth = (());
("The first day of the month: " + firstDayOfMonth); //The first day of this month: 2023-10-01("Last day of the month: " + lastDayOfMonth);//The last day of the month: 2023-10-31

3. Get the current week of the year and the week of the month

// Get the current dateLocalDate currentDate = ();
// Get WeekFields object, specifying the start date of the week as Monday//4 Thursday was designated as the first day of the year.  This affects how the first week of the year is defined.  Under this definition, the first week of the year will include Thursday// Therefore the week on Thursday will be considered the first week until the Thursday of the following year.WeekFields weekFields = (,4);
// Get the current date week that is the week of the monthint weekOfMonth = (());
// Get what week the current date is the current week of the yearint weekOfYear = (());
("The current date is the first of this month" + weekOfMonth + " week");
("The current date is the first of the year" + weekOfYear + " week");

Some introductions about TemporalAdjusters

TemporalAdjustersis a practical tool class in Java 8 that provides some built-in tool methods for date and time adjustment. These methods allow you to perform complex date and time adjustment operations, such as getting the first day of a certain month, getting the next Monday, getting the last day of the year, etc.TemporalAdjustersThe method in  returnTemporalAdjusterObject, this is a functional interface used inAdjust date and time in the framework.

Here are some common onesTemporalAdjustersMethods and their functions:

firstDayOfMonth(): Returns the first day of the month where the specified date is.

lastDayOfMonth(): Returns the last day of the month where the specified date is.

firstDayOfNextMonth(): Returns the first day of the next month on the specified date.

firstDayOfNextYear(): Returns the first day of the next year on the specified date.

next(DayOfWeek dayOfWeek): Returns the next week after the specified date. For example,next()Return to the next Monday.

previous(DayOfWeek dayOfWeek): Returns the previous week before the specified date.

nextOrSame(DayOfWeek dayOfWeek): Returns the specified date, if it is the specified day of the week, it returns itself, otherwise it returns the next specified day of the week.

previousOrSame(DayOfWeek dayOfWeek): Returns the specified date, if it is the specified day of the week, it returns itself, otherwise it returns the previous specified day of the week.

firstInMonth(DayOfWeek dayOfWeek): Returns the first specified day of the week in the month where the specified date is.

lastInMonth(DayOfWeek dayOfWeek): Returns the last specified day of the week of the month where the specified date is.

dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek): Returns the month of the specified dateordinalA designated day of week. For example,dayOfWeekInMonth(2, )Returns the second Wednesday of the month where the specified date is.

firstDayOfYear(): Returns the first day of the year the specified date is located.

lastDayOfYear(): Returns the last day of the year the specified date is located.

Usage 5: Date comparison:

1. equals() method:

The equals() method is used to check whether two LocalDate objects represent the same date. If two objects represent the same date, the equals() method will return true, otherwise false.

LocalDate date1 = (2023, 5, 15);
LocalDate date2 = (2023, 5, 15);
LocalDate date3 = (2023, 5, 16);
boolean areEqual  = (date2); // Return trueboolean areEqual2 = (date3); // return false

() method:

The isBefore() method is used to check whether one LocalDate is before another LocalDate. If the first date is before the second date, the method returns true, otherwise it returns false.

LocalDate date1 = (2023, 5, 15);
LocalDate date2 = (2023, 5, 20);
boolean isBefore  = (date2); // Return trueboolean isBefore2 = (date1); // return false

() method:

The isAfter() method is used to check whether one LocalDate is after another LocalDate. If the first date is after the second date, the method returns true, otherwise it returns false.

LocalDate date1 = (2023, 5, 15);
LocalDate date2 = (2023, 5, 10);
boolean isAfter = (date2); // return true

() method:

The compareTo() method is used to compare two LocalDate objects and return an integer value. If the first date is before the second date, it returns a negative number; if the two dates are the same, it returns a zero; if the first date is after the second date, it returns a positive number.

LocalDate date1 = (2023, 5, 15);
LocalDate date2 = (2023, 5, 20);
int result = (date2); // Return to -5int result2 = (date1); // return5

Attachment: The implementation method of using LocalDate to calculate age based on dates in Java

Example 1: Calculate age based on date of birth and current date

This example will show how to use LocalDate to calculate a person's age. Assuming the current date is July 31, 2021, we want to calculate the age of a person when he was born on October 24, 1995. The following is the code to implement the method, where the "xxxx-xx-xx" part in the code block needs to be replaced with a specific year, month and day:

LocalDate birthDate = (1995, , 24);
LocalDate currentDate = ();

int age = (birthDate, currentDate).getYears();

("Age: " + age);

The output result is:

Age: 25

Example 2: Calculate age based on birthday string

This example will show how to use LocalDate to calculate a person's age. Assuming the current date is July 31, 2021, we have a string "1995-10-24" containing the birthday, and we want to calculate the age of this person. Here is the code to implement the method:

DateTimeFormatter formatter = ("yyyy-MM-dd");
LocalDate birthDate = ("1995-10-24", formatter);
LocalDate currentDate = ();

int age = (birthDate, currentDate).getYears();

("Age: " + age);

The output result is:

Age: 25

Summarize

This is the end of this article about the detailed usage of the date LocalDate class in JAVA. For more related contents of the date LocalDate class, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!