Java - Program to get yesterday's date.


IncludeHelp 12 September 2016

In this code snippet/program we will learn how to get/print yesterday's date in specific format using calendar class?

In this program we are getting yesterday's date by subtracting current date from 1 and then formatting date in "dd MMM yyyy" format.

To format date we are using DateFormat calss.

Java Code Snippet - Java program to get yesterday's Date

//Java - Program to get yesterday’s date.

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

class ExGetYesterdayDate
{
	public static void main(String args[])
	{
		//variable to store date in string format
		String yesterdayDate=null; 
		
		//to get calendar instance 
		Calendar cal = Calendar.getInstance();
		
		//subtract 1 from calendar current date 
		cal.add(Calendar.DATE, -1);
		
		//format date
		DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
		
		//get formatted date
		yesterdayDate=dateFormat.format(cal.getTime());
		
		System.out.println("Yesterday's date = "+ yesterdayDate);		
	}
}
    

    Yesterday's date = 11 Sep 2016



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.