Tuesday 10 September 2013

Generating previous day's Date using Java

Purpose: Generating previous day's Date using Java


Some times we may need to use date in different situations in different applications dynamically. That is very simple and we can use the methods of Date/Calender class. But some times we may need to capture previous day's date.

Following code will be useful to capture previous day's date.

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

public class PreviousDate {
 public static void main(String[] args)
 {
//     Selecting Previous Date --- Start
    
     DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
     Date date = new Date();
     Calendar cal = new GregorianCalendar();
     cal.setTime(date);
     cal.add(Calendar.DAY_OF_YEAR,-1);
     Date oneDayBefore= cal.getTime();
     System.out.println();
     System.out.println("Previous Day's Date in dd/mm/yyyy format: "+dateFormat.format(oneDayBefore).toString());
//     Selecting Previous Date --- End
 }
}
 

No comments:

Post a Comment