Monthly Archives: April 2012

Java Calendar object manipulation

Code snippet to generate first day of month and last day of a particular month. It comes in handy if you have an automated process that will run on the first of the current month to pull data from the previous month.

 


Calendar firstDayMonth = null;
Calendar lastDayMonth = null;

//initialize calendar
firstDayMonth = Calendar.getInstance();
lastDayMonth = Calendar.getInstance();
firstDayMonth.add(Calendar.MONTH, -1);
firstDayMonth.set(Calendar.DAY_OF_MONTH, 1);
firstDayMonth.set(Calendar.HOUR, 00);
firstDayMonth.set(Calendar.MINUTE, 00);
firstDayMonth.set(Calendar.SECOND, 00);
firstDayMonth.set(Calendar.MILLISECOND, 00);

lastDayMonth.add(Calendar.MONTH, -1);
lastDayMonth.set(Calendar.DAY_OF_MONTH, lastDayMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
lastDayMonth.set(Calendar.HOUR, 23);
lastDayMonth.set(Calendar.MINUTE, 59);
lastDayMonth.set(Calendar.SECOND, 59);
lastDayMonth.set(Calendar.MILLISECOND, 99);


 

 

If you run the code above in April, firstDayMonth Calendar object would be 2012-03-01 00:00:00 and lastDayMonth would be 2012-03-31 23:59:59