Java LocalDate Class
LocalDate is an immutable date class introduced in Java 8, which belongs to thejava.timepackage.
LocalDate represents a date without a timezone (year-month-day), such as "2023-05-15". LocalDate does not contain time and timezone information, making it very suitable for scenarios that only require dates, such as birthdays and holidays.
Main Features of LocalDate
1. Immutability
LocalDate instances are immutable; any modification operation returns a new LocalDate object instead of modifying the original object.
2. Thread Safety
Due to immutability, LocalDate is thread-safe and can be safely used in multi-threaded environments.
3. ISO-8601 Standard
LocalDate follows the ISO-8601 calendar system, which is the international standard for modern date and time representation.
Creating LocalDate Objects
1. Getting the Current Date
LocalDate today = LocalDate.now();
System.out.println("今天的日期: " + today);
2. Creating with a Specific Date
LocalDate specificDate = LocalDate.of(2023, Month.MAY, 15); // 或者 LocalDate specificDate2 = LocalDate.of(2023, 5, 15);
3. Parsing from a String
LocalDate parsedDate = LocalDate.parse("2023-05-15");
Common Operation Methods
1. Getting Date Information
Example
int year = date.getYear(); // 2023
Month month = date.getMonth(); // MAY
int day = date.getDayOfMonth(); // 15
DayOfWeek dow = date.getDayOfWeek(); // MONDAY
int len = date.lengthOfMonth(); // 31 (days in May)
boolean leap = date.isLeapYear(); // false (2023 is not a leap year)
2. Date Addition and Subtraction
Example
LocalDate nextWeek = today.plusWeeks(1);
LocalDate nextMonth = today.plusMonths(1);
LocalDate nextYear = today.plusYears(1);
LocalDate yesterday = today.minusDays(1);
3. Date Comparison
Example
LocalDate date2 = LocalDate.of(2023, 6, 20);
boolean isBefore = date1.isBefore(date2); // true
boolean isAfter = date1.isAfter(date2); // false
boolean isEqual = date1.isEqual(date2); // false
4. Adjusting Dates
Example
LocalDate firstDayOfMonth = date.withDayOfMonth(1);
LocalDate lastDayOfYear = date.with(TemporalAdjusters.lastDayOfYear());
Formatting and Parsing
1. Formatting Dates
Example
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String formattedDate = date.format(formatter);
2. Parsing a String into a Date
Example
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate date = LocalDate.parse(dateStr, formatter);
Practical Application Examples
1. Calculating the Number of Days Between Two Dates
Example
LocalDate endDate = LocalDate.of(2023, 5, 15);
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("Days difference: " + daysBetween);
2. Checking if a Date is Within a Range
Example
LocalDate startDate = LocalDate.of(2023, 5, 1);
LocalDate endDate = LocalDate.of(2023, 5, 31);
if (dateToCheck.isAfter(startDate) && dateToCheck.isBefore(endDate)) {
System.out.println("Date is within the range");
}
3. Getting All Dates of a Month
Example
int daysInMonth = date.lengthOfMonth();
for (int i = 1; i <= daysInMonth; i++) {
System.out.println(date.withDayOfMonth(i));
}
Comprehensive Example
Example
import java.time.Month;
import java.time.DayOfWeek;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
public class LocalDateDemo {
public static void main(String[] args) {
// 1. Creating LocalDate instances
System.out.println("=== Creating LocalDate instances ===");
LocalDate today = LocalDate.now();
LocalDate specificDate = LocalDate.of(2023, Month.JULY, 15);
LocalDate parsedDate = LocalDate.parse("2023-08-20");
System.out.println("Current date: " + today);
System.out.println("Specific date: " + specificDate);
System.out.println("Parsed date: " + parsedDate);
// 2. Getting date information
System.out.println("\n=== Getting date information ===);
System.out.println("Year: " + today.getYear());
System.out.println("Month: " + today.getMonth() + " (" + today.getMonthValue() + ")");
System.out.println("Day: " + today.getDayOfMonth());
System.out.println("Day of week: " + today.getDayOfWeek());
System.out.println("Day of year: " + today.getDayOfYear());
System.out.println("Days in month: " + today.lengthOfMonth());
System.out.println("Days in year: " + today.lengthOfYear());
System.out.println("Is leap year: " + today.isLeapYear());
// 3. Date calculation
System.out.println("\n=== Date calculation ===);
System.out.println("Plus 5 days: " + today.plusDays(5));
System.out.println("Plus 2 weeks: " + today.plusWeeks(2));
System.out.println("Plus 3 months: " + today.plusMonths(3));
System.out.println("Minus 1 year: " + today.minusYears(1));
System.out.println("First day of next month: " + today.plusMonths(1).withDayOfMonth(1));
System.out.println("Last day of this month: " + today.withDayOfMonth(today.lengthOfMonth()));
// 4. Date comparison
System.out.println("\n=== Date comparison ===);
LocalDate date1 = LocalDate.of(2023, 6, 15);
LocalDate date2 = LocalDate.of(2023, 6, 20);
System.out.println(date1 + " is " + date2 + " before? " + date1.isBefore(date2));
System.out.println(date1 + " is " + date2 + " after? " + date1.isAfter(date2));
System.out.println(date1 + " equals " + date2 + "? " + date1.isEqual(date2));
// 5. Calculating date difference
System.out.println("\n=== Calculating date difference ===);
LocalDate startDate = LocalDate.of(2023, 1, 1);
LocalDate endDate = LocalDate.of(2023, 12, 31);
System.out.println("Days between two dates: " + ChronoUnit.DAYS.between(startDate, endDate));
System.out.println("Months between two dates: " + ChronoUnit.MONTHS.between(startDate, endDate));
System.out.println("Years between two dates: " + ChronoUnit.YEARS.between(startDate, endDate));
// 6. Date formatting
System.out.println("\n=== Date formatting ===);
DateTimeFormatter basicFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
DateTimeFormatter chineseFormatter = DateTimeFormatter.ofPattern(yyyy-MM-dd EEEE, Locale.CHINA);
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MMM dd, yyyy", Locale.US);
System.out.println("Basic format: " + today.format(basicFormatter));
System.out.println("Chinese format: " + today.format(chineseFormatter));
System.out.println("English format: " + today.format(customFormatter));
// 7. Other useful methods
System.out.println("\n=== Other useful methods ===);
System.out.println("Adjusted to next Monday: " + today.with(DayOfWeek.MONDAY));
System.out.println("Is weekend: " +
(today.getDayOfWeek() == DayOfWeek.SATURDAY || today.getDayOfWeek() == DayOfWeek.SUNDAY));
// 8. Date range iteration
System.out.println("\n=== Date range iteration ===);
System.out.println("Dates for the next 7 days:");
today.datesUntil(today.plusDays(7))
.forEach(System.out::println);
}
}
The output will be similar to the following:
=== 创建 LocalDate 实例 === 当前日期: 2023-06-15 特定日期: 2023-07-15 解析日期: 2023-08-20 === 获取日期信息 === 年: 2023 月: JUNE (6) 日: 15 星期: THURSDAY 一年中的第几天: 166 月份天数: 30 年份天数: 365 是否闰年: false === 日期计算 === 加5天: 2023-06-20 加2周: 2023-06-29 加3个月: 2023-09-15 减1年: 2022-06-15 下个月的第一天: 2023-07-01 本月的最后一天: 2023-06-30 === 日期比较 === 2023-06-15 在 2023-06-20 之前? true 2023-06-15 在 2023-06-20 之后? false 2023-06-15 等于 2023-06-20? false === 计算日期差 === 两个日期之间的天数: 364 两个日期之间的月数: 11 两个日期之间的年数: 0 === 日期格式化 === 基本格式: 2023/06/15 中文格式: 2023年06月15日 星期四 英文格式: Jun 15, 2023 === 其他实用方法 === 调整到下个星期一: 2023-06-19 是否是周末: false === 日期范围迭代 === 接下来7天的日期: 2023-06-15 2023-06-16 2023-06-17 2023-06-18 2023-06-19 2023-06-20 2023-06-21
Summary
The LocalDate class is an important part of the Java 8 Date-Time API. It provides rich methods for handling date-related operations. Compared to the old Date and Calendar classes, LocalDate is more intuitive, easier to use, and thread-safe. Mastering LocalDate can greatly improve the efficiency of date handling and code readability.
The following are its common methods:
Static Factory Methods
| Method | Description | Example |
|---|---|---|
static LocalDate now() |
Get the current date | LocalDate.now() |
static LocalDate of(int year, int month, int dayOfMonth) |
Create with a specified year, month, and day | LocalDate.of(2023, 6, 15) |
static LocalDate of(int year, Month month, int dayOfMonth) |
Create with a specified year, month, and day (using the Month enum) | LocalDate.of(2023, Month.JUNE, 15) |
static LocalDate parse(CharSequence text) |
Parse from a string (ISO format: yyyy-MM-dd) | LocalDate.parse("2023-06-15") |
static LocalDate parse(CharSequence text, DateTimeFormatter formatter) |
Parse using a specified format | LocalDate.parse("15/06/2023", DateTimeFormatter.ofPattern("dd/MM/yyyy")) |
Getting Date Information
| Method | Description | Example |
|---|---|---|
int getYear() |
Get the year | 2023 |
Month getMonth() |
Get the month (Month enum) | Month.JUNE |
int getMonthValue() |
Get the month value (1-12) | 6 |
int getDayOfMonth() |
Get the day of the month | 15 |
int getDayOfYear() |
Get the day of the year | 166 |
DayOfWeek getDayOfWeek() |
Get the day of the week (DayOfWeek enum) | DayOfWeek.THURSDAY |
int lengthOfMonth() |
Return the number of days in the month | 30 |
int lengthOfYear() |
Return the number of days in the year (365 or 366) | 365 |
boolean isLeapYear() |
Check if it is a leap year | false |
Date Operations
| Method | Description | Example |
|---|---|---|
LocalDate plusDays(long days) |
Add days | date.plusDays(5) |
LocalDate plusWeeks(long weeks) |
Add weeks | date.plusWeeks(2) |
LocalDate plusMonths(long months) |
Add months | date.plusMonths(3) |
LocalDate plusYears(long years) |
Add years | date.plusYears(1) |
LocalDate minusDays(long days) |
Subtract days | date.minusDays(5) |
LocalDate minusWeeks(long weeks) |
Subtract weeks | date.minusWeeks(2) |
LocalDate minusMonths(long months) |
Subtract months | date.minusMonths(3) |
LocalDate minusYears(long years) |
Subtract years | date.minusYears(1) |
LocalDate withDayOfMonth(int dayOfMonth) |
Modify the day of the month | date.withDayOfMonth(1) |
LocalDate withDayOfYear(int dayOfYear) |
Modify the day of the year | date.withDayOfYear(100) |
LocalDate withMonth(int month) |
Modify the month | date.withMonth(12) |
LocalDate withYear(int year) |
Modify the year | date.withYear(2024) |
Date Comparison
| Method | Description | Example |
|---|---|---|
boolean isAfter(ChronoLocalDate other) |
Check if after the specified date | date1.isAfter(date2) |
boolean isBefore(ChronoLocalDate other) |
Check if before the specified date | date1.isBefore(date2) |
boolean isEqual(ChronoLocalDate other) |
Check if equal to the specified date | date1.isEqual(date2) |
long until(ChronoLocalDate endDate, ChronoUnit unit) |
Calculate the amount of time between two dates | date1.until(date2, ChronoUnit.DAYS) |
Formatting and Conversion
| Method | Description | Example |
|---|---|---|
String format(DateTimeFormatter formatter) |
Format as a string | date.format(DateTimeFormatter.ISO_DATE) |
String toString() |
Convert to an ISO format string (yyyy-MM-dd) | "2023-06-15" |
long toEpochDay() |
Convert to the number of days since 1970-01-01 | 19531 |
LocalDateTime atTime(int hour, int minute) |
Convert to LocalDateTime | date.atTime(14, 30) |
LocalDateTime atTime(LocalTime time) |
Convert to LocalDateTime | date.atTime(LocalTime.now()) |
Other Useful Methods
| Method | Description | Example |
|---|---|---|
boolean isSupported(ChronoUnit unit) |
Check if time unit is supported | date.isSupported(ChronoUnit.DAYS) |
boolean isSupported(ChronoField field) |
Check if time field is supported | date.isSupported(ChronoField.HOUR_OF_DAY) |
LocalDate with(TemporalAdjuster adjuster) |
Adjust date using an adjuster | date.with(TemporalAdjusters.firstDayOfMonth()) |
Java java.nio.file.Files