Program to get yesterday’s date in Java

In this Java program, you will learn how to retrieve yesterday’s date, then print it out to the console.

The concept is easy; get today’s date and substrate one day from it.

The output will be formatted as MM/DD/YYYY

Get yesterday’s Date using Java

package cp;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Main {
  public static void main(String args[]) {

    String yesterdayDate = null;

    //Initiate a calendar instance
    Calendar calendar = Calendar.getInstance();

    //subtract 1 date from current date
    calendar.add(Calendar.DATE, -1);

    //format date
    DateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY");

    //get formatted date
    yesterdayDate = dateFormat.format(calendar.getTime());

    System.out.println("Yesterday's date is " + yesterdayDate);
  }
}

Output

Yesterday’s date is 11/23/2020

 

Leave a Comment