Get yesterdays date by no of days in Java
In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date. After that there are two ways to get the yesterday’s date: one way is to use the Hour field of the Calendar class and other is to use the field DAY_OF_MONTH of the Calendar class.
Example:
If the current date is:22-12-2021
Then the previous date is: 21-12-2021
Program
Filename: YesterdayDate.java
// Program for finding yesterday's date using the no of days in the calendar
//importing the required packages
import java.io.*;
import java.util.*;
import java.util.Calendar;
// main class
public class YesterdayDate {
public static void main(String[] args) throws Exception{
// the calendar class consists of the days
Calendar calendar_days = Calendar.getInstance();
// 24 hours make a day. Therefore, we have used -24 to retrieve the previous day.
calendar_days.add(Calendar.HOUR, -24);
System.out.println(calendar_days.getTime()); // prints previous date
Calendar calendars2 = Calendar.getInstance();
// DAY_OF_MONTH gives the current day and -1 to fetch the previous day.
calendars2.add(Calendar.DAY_OF_MONTH, -1);
System.out.println(calendars2.getTime()); // prints previous date
}
}
Output
Sun Nov 20 17:23:46 GMT 2022
Sun Nov 20 17:23:46 GMT 2022