Get Yesterday’s Date in Java
In Java, you can use the java.time.LocalDate class and java.time.format.DateTimeFormatter class to obtain the year, month, and day of yesterday.
Here is a sample code:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minusDays(1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String yesterdayFormatted = yesterday.format(formatter);
System.out.println("昨天的年月日:" + yesterdayFormatted);
}
}
The output is similar to:
昨天的年月日:2022-03-31
In the sample code, the current date is first obtained using LocalDate.now(), and then yesterday’s date is obtained using the minusDays(1) method. Next, the date is formatted to the specified format using DateTimeFormatter (in this case, “yyyy-MM-dd”), and finally the formatted date is printed.