Pages

Monday, March 5, 2012

Finding first/last day of the previous month using Calendar class in Java

Calendar is an abstract base class and implements Serializable and Cloneable interfaces.

Calendar provides 'getInstance' class method, returns Calendar object whose time fields have been initialized with the current date and time.
Calendar presentTime = Calendar.getInstance();

To find the last day/first day of the month
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class FindHistDate{ public static void getLastMonthLastDate() { 

 SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); 
 Calendar calendar = Calendar.getInstance();
 calendar.add(Calendar.MONTH, -1); 
 int max = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
 calendar.set(Calendar.DAY_OF_MONTH, max);
 Date pme = calendar.getTime();
 System.out.println(sdf.format(pme));

 int min = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
 calendar.set(Calendar.DAY_OF_MONTH, min);
 Date pms = calendar.getTime();
 System.out.println(pms);
}
 public static void main(String[] args) {
 FindHistDate.getLastMonthLastDate();
 }
}
o/p:
29-Feb-2012
Wed Feb 01 11:24:27 IST 2012