Get yesterday date from LocalDate in Java
In Java, there are several ways to get the most recent day or hour.
In LocalDate Java8, the java.time package now includes Date classes related to Java 8.
In the example provided, we only employ the dateFormat.format(cal.getTime()) function to obtain the current date. However, if you add a day to the calendar by using the command cal.add(Calendar.DATE, -1), the commanddateFormat.format(cal.getTime()) will show the date from the previous day.
These are the procedures.
- Use the Localdate.now() method to retrieve the current date. LocalDate is a Date class that contains date info alone without period and zone details.
- Apply minusDays() method on it retrieves days that have passed.
Example1: CurrentdateYesterday.java
//this program is for getting yesterday's date by using the LocalDate class in Java
//importing the required packages
import java.io.*;
import java.util.*;
import java.time.LocalDate;
public class CurrentdateYesterday {
//main section of the program
public static void main(String[] args) throws Exception{
// the object currdate is used for storing the current date value
LocalDate currDate = LocalDate.now();
//displays the current date from the Calendar class
System.out.println("The current date is: "+currDate);
LocalDate yesterDay = currDate.minusDays(1);
// displays the previous day
System.out.println("The previous date is: "+yesterDay);
}
}
Output
The current date is: 2022-11-19
The previous date is: 2022-11-18
Instead of LocalDate, you should use the [LocalDateTime] class if you want the prior date and time.
Example2: CurrentTimedate.java
//the program is for getting yesterday's date by using the LocalDate class in Java
//importing the required packages
import java.io.*;
import java.util.*;
import java.time.LocalDateTime;
//class CurrentTimedate
public class CurrentTimedate {
public static void main(String[] args) throws Exception{
LocalDateTime currDate = LocalDateTime.now();
//displays the current date and also the timestamp
System.out.println(currDate);
LocalDateTime yesterDay = currDate.minusDays(1);
//displays yesterday date and also the timestamp
System.out.println(yesterDay);
}
}
Output
2022-11-19T17:32:31.265357
2022-11-18T17:32:31.265357