Get the first and last date of the previous month

Possible duplicate:
How to get the first date and last date of the previous month? (Java)

In java, how to get the first and last date of the previous month?

If I am not mistaken, the following code should receive the last date of the previous month.

Calendar aCalendar = Calendar.getInstance(); aCalendar.set(Calendar.DAY_OF_MONTH, -1); aCalendar.add(Calendar.DAY_OF_MONTH, -1) ; System.out.println(new Timestamp(aCalendar.getTime().getTime())); 

Correct me if I am wrong.

Thanks.

+8
java date datetime calendar
source share
2 answers

Use getActualMaximum()

 Calendar aCalendar = Calendar.getInstance(); // add -1 month to current month aCalendar.add(Calendar.MONTH, -1); // set DATE to 1, so first date of previous month aCalendar.set(Calendar.DATE, 1); Date firstDateOfPreviousMonth = aCalendar.getTime(); // set actual maximum date of previous month aCalendar.set(Calendar.DATE, aCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)); //read it Date lastDateOfPreviousMonth = aCalendar.getTime(); 
+29
source share
 Calendar aCalendar = Calendar.getInstance(); aCalendar.set(Calendar.DATE, 1); aCalendar.add(Calendar.DAY_OF_MONTH, -1); Date lastDateOfPreviousMonth = aCalendar.getTime(); aCalendar.set(Calendar.DATE, 1); Date firstDateOfPreviousMonth = aCalendar.getTime(); 
+15
source share

All Articles