Java uses LocalDate to get the previous day's date

Problem Description:

When making a query, if the user does not select the start time and end time of the query, we want to query the data of the previous day by default. In this case, how to get the date of the previous day?

Go directly to the code:

LocalDate localDate = LocalDate.now(); //获取今天的日期
LocalDate yesterday = localDate.plusDays(-1); //前一天日期是今天减1
// LocalDate yesterday = localDate.minusDays(1); //两种用法均可

// 依次输出年月日
System.out.println(yesterday.getYear()); //年份
System.out.println(yesterday.getMonthValue()); //月份
System.out.println(yesterday.getDayOfMonth()); //日

Advanced:

When we want to limit the query to all the data of the previous day, we can use to LocalTimegive the minimum value 00:00:00 and the maximum value 23:59:59 of yesterday's time. code show as below:

LocalDate localDate = LocalDate.now(); //获取今天的日期
LocalDate yesterday = localDate.plusDays(-1); //前一天日期是今天减1

startTime = LocalDateTime.of(yesterday, LocalTime.MIN); 
endTime = LocalDateTime.of(yesterday, LocalTime.MAX);

Related links: Java uses LocalDate to get the first and last day of a month

Guess you like

Origin blog.csdn.net/qq_39691492/article/details/121165346