LocalDate class: Detailed explanation of dates in JAVA

Table of contents

Usage 1: Get some information about the current date:

1. Get the current date

2. Get basic information such as current year, month, day, etc.

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

Usage 2: Create a specific date

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

1. Increase or decrease the specified number of years.

2. Increase or decrease the specified number of months.

3. Increase or decrease the specified number of weeks.

4. Increase or decrease the specified number of days.

5. In addition to separate operations for the year, month, and Sunday, we can also perform unified operations, such as adding one year and three months (plus means increase, minus means decrease)

Usage 4: Get the specific time of the week, month and other information of the current time

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

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

3. Get the week where the current time is located in this year and the week of this month

 Some introduction to TemporalAdjusters

Usage 5: Comparison of dates:

1. equals() method

2.isBefore() method

3.isAfter() method

4.compareTo() method


java.time.LocalDate is one of the date classes introduced in Java 8 and is located in the java.time package. It provides a simple way to represent dates without including time and time zone information. Below we will explain its various uses.

Usage 1: Get some information about the current date:

LocalDate represents a date of year, month and day, its general form is: yyyy-MM-dd. For example: 2023-10-11. LocalDate在JAVA中由final修饰, is immutable, once created, its value cannot be changed. If you need to modify the date, you can create a newLocalDateobject.

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

LocalDate currentDate = LocalDate.now();//创建一个LocalData对象获取当前日期
System.out.println("当前日期为:"+currentDate);

The output is:

The current date is: 2023-10-11

2. In addition to getting the entire date, you can also get basic information such as the current year, month, day, etc.

// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 获取年份
int year = currentDate.getYear();
// 获取月份
Month month = currentDate.getMonth();
// 获取日
int day = currentDate.getDayOfMonth();
System.out.println("年份: " + year);
System.out.println("月份: " + month);
System.out.println("日: " + day);

The output result is: (If you want to get the month in int form, you can use: int monthValue = currentDate.getMonthValue();)

Year: 2023
Month: OCTOBER
Day: 11 

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

LocalDate currentDate = LocalDate.now();
// 获取星期几枚举值
DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
// 获取日期在年份中的第几天
int dayOfYear = currentDate.getDayOfYear();
// 检查日期所在年份是否为闰年
boolean isLeapYear = currentDate.isLeapYear();
// 获取日期所在月份的天数
int daysInMonth = currentDate.lengthOfMonth();
// 获取日期所在年份的天数
int daysInYear = currentDate.lengthOfYear();
// 获取星期几的整数值
int dayOfWeekValue = currentDate.getDayOfWeek().getValue();
System.out.println("当前日期: " + currentDate);             //当前日期: 2023-10-11
System.out.println("今天是星期 " + dayOfWeekValue);         //今天是星期 3
System.out.println("星期几: " + dayOfWeek);                //星期几: WEDNESDAY
System.out.println("日期在年份中的第几天: " + dayOfYear);    //日期在年份中的第几天: 284
System.out.println("是否为闰年: " + isLeapYear);           //是否为闰年: false
System.out.println("当前月份的天数: " + daysInMonth);      //当前月份的天数: 31
System.out.println("当前年份的天数: " + daysInYear);       //当前年份的天数: 365

Usage 2: Create a specific date: LocalDate.of、LocalDate.parse

You can useLocalDate.of(year, month, day) to create a specific date object

LocalDate currentDate1 = LocalDate.of(2023,10,22);
System.out.println("当前日期为:"+currentDate1);

The output is:

The current date is: 2023-10-22

In addition to using , is used to parse a string representation of a date into a object. It allows you to convert a string date into a date object according to the specified date format for subsequent operations or display. LocalDate.of来创造一个特定的日期对象外,我们还可以将一个格式标准的String对象转化为LocalData对象:LocalDate.parse LocalDate.parseLocalDate

//创建一个字符串日期
String stringdata="2023-01-06";
//格式化日期规则
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//将字符串日期按照规则转化为LocalData对象
LocalDate stringcurrentDate1= LocalDate.parse(stringdata,formatter);
System.out.println("当前日期为:"+stringcurrentDate1);

The output result is: ( It should be noted that the date format you specify should be: yyyy-MM-dd, you cannot write 2023-1-06, otherwise Will throw: java.time.format.DateTimeParseException: Exception)

The current date is: 2023-01-06

 The scenario of converting a string date into a LocalData object is mostly used to read the date in the file. When doing business, the date is often read from Excel, Word or image recognition invoice and other data. Sometimes these dates are not It will be in a standardized 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 to format the date. Just set the value to yyyy-M-d to read it, and pad it with zeros if necessary.

// 原始日期字符串
String originalDate = "2023-1-1";
// 将日期字符串解析为 LocalDate 对象
LocalDate date = LocalDate.parse(originalDate, DateTimeFormatter.ofPattern("yyyy-M-d"));
System.out.println("格式化前的日期:" + originalDate);
// 使用 DateTimeFormatter 格式化日期,指定月份和日期部分的宽度为两位
String formattedDate = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println("格式化后的日期:" + formattedDate);

The output is:

Date before formatting: 2023-1-1
Date after formatting: 2023-01-01

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

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

LocalDate date = LocalDate.now();
LocalDate futureDate = date.plusYears(2); // 增加2年
LocalDate pastDate = date.minusYears(1); // 减少1年
System.out.println("增加后的年数:"+futureDate);//增加后的年数:2025-10-11
System.out.println("减少后的年数:"+pastDate);//减少后的年数:2022-10-11

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

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

4.plusDays(long days), minusDays(long days): Increase or decrease the specified number of days. (The function form is the same, so there is no code display on every day of the month)

5. In addition to separate operations for the year, month, and Sunday, we can also perform unified operations, such as adding one year and three months (plus means increase, minus means decrease)

LocalDate date = LocalDate.now();
LocalDate futureDate = date.plus(Period.of(1, 2, 0)); // 增加1年3个月
System.out.println("当 前 日 期:"+date);       //当 前 日 期:2023-10-11
System.out.println("增加后的日期:"+futureDate);//增加后的日期:2024-12-11

Usage 4: Get the specific time of the week, month and other information of the current time

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

LocalDate currentDate = LocalDate.now();
// 获取当前周的第一天(星期一)
LocalDate firstDayOfWeek = currentDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
// 获取当前周的最后一天(星期日)
LocalDate lastDayOfWeek = currentDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
System.out.println("本周第一天: " + firstDayOfWeek); //本周第一天: 2023-10-09
System.out.println("本周最后一天: " + lastDayOfWeek);//本周最后一天: 2023-10-15

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

// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 获取当前月的第一天
LocalDate firstDayOfMonth = currentDate.with(TemporalAdjusters.firstDayOfMonth());
// 获取当前月的最后一天
LocalDate lastDayOfMonth = currentDate.with(TemporalAdjusters.lastDayOfMonth());
System.out.println("本月第一天: " + firstDayOfMonth); //本月第一天: 2023-10-01
System.out.println("本月最后一天: " + lastDayOfMonth);//本月最后一天: 2023-10-31

3. Get the week where the current time is located in this year and the week of this month

// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 获取 WeekFields 对象,指定周的起始日为星期一
//4 指定了星期四作为一年中的第一天。这影响了一年中的第一周是如何定义的。在这种定义下,一年中的第一周将包含星期四
// 因此星期四所在的周将被视为第一周,直到下一年的星期四。
WeekFields weekFields = WeekFields.of(DayOfWeek.MONDAY,4);
// 获取当前日期所在周是本月的第几周
int weekOfMonth = currentDate.get(weekFields.weekOfMonth());
// 获取当前日期所在周是本年的第几周
int weekOfYear = currentDate.get(weekFields.weekOfWeekBasedYear());
System.out.println("当前日期所在周是本月的第 " + weekOfMonth + " 周");
System.out.println("当前日期所在周是本年的第 " + weekOfYear + " 周");

 aboutTemporalAdjusters的一些简介

TemporalAdjusters is a utility class in Java 8 that provides some built-in utility 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 month, getting the next Monday, getting the last day of the year, etc. Methods in TemporalAdjusters return TemporalAdjuster objects, which is a functional interface for date and time adjustments in the java.time framework .

Here are some common TemporalAdjusters methods and their functions:

  1. firstDayOfMonth(): Returns the first day of the month in which the specified date falls.

  2. lastDayOfMonth(): Returns the last day of the month for the specified date.

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

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

  5. next(DayOfWeek dayOfWeek): Returns the next day of the week after the specified date. For example, next(DayOfWeek.MONDAY) returns the next Monday.

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

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

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

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

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

  11. dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek): Returns the ordinal specified day of the week in the month where the specified date falls. For example, dayOfWeekInMonth(2, DayOfWeek.WEDNESDAY) returns the second Wednesday of the month for the specified date.

  12. firstDayOfYear(): Returns the first day of the year for the specified date.

  13. lastDayOfYear(): Returns the last day of the year for the specified date.

Usage 5: Comparison of dates:

1. equals() method : equals() method is used to check two < a i=4> Whether the objects represent the same date. The method returns if the two objects represent the same date, otherwise. LocalDateequals()truefalse

LocalDate date1 = LocalDate.of(2023, 5, 15);
LocalDate date2 = LocalDate.of(2023, 5, 15);
LocalDate date3 = LocalDate.of(2023, 5, 16);
boolean areEqual  = date1.equals(date2); // 返回 true
boolean areEqual2 = date1.equals(date3); // 返回 false

2.isBefore() method: isBefore() method is used to check a LocalDate before anotherLocalDate. This method returns true if the first date is before the second date, false otherwise.

LocalDate date1 = LocalDate.of(2023, 5, 15);
LocalDate date2 = LocalDate.of(2023, 5, 20);
boolean isBefore  = date1.isBefore(date2); // 返回 true
boolean isBefore2 = date2.isBefore(date1); // 返回 false

3.isAfter() method : isAfter() method is used to check a LocalDate after anotherLocalDate. This method returns true if the first date is after the second date, false otherwise.

LocalDate date1 = LocalDate.of(2023, 5, 15);
LocalDate date2 = LocalDate.of(2023, 5, 10);
boolean isAfter = date1.isAfter(date2); // 返回 true

4.compareTo() method: compareTo() method is used to compare two< a i=4> objects are compared and an integer value is returned. If the first date is before the second date, a negative number is returned; if the two dates are the same, zero is returned; if the first date is after the second date, a positive number is returned. LocalDate

LocalDate date1 = LocalDate.of(2023, 5, 15);
LocalDate date2 = LocalDate.of(2023, 5, 20);
int result = date1.compareTo(date2); // 返回-5
int result2 = date2.compareTo(date1); // 返回5

For the time being, I have encountered these during development. If there is valuable information in the future, I will continue to add it. If you find it useful, please like it. If you need it, you can also click it to favorites.

Guess you like

Origin blog.csdn.net/jialuosi/article/details/133770363
Recommended