18

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 wrong the following code is to get 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.

Thank you.

Community
  • 1
  • 1
  • 1
    You say "*Correct me if I am wrong*". What do you see when you run this code? – Lion Aug 17 '12 at 10:08
  • @keppil: Thank you it helped and sorry I missed to view the link before I post this. –  Aug 17 '12 at 10:21

2 Answers2

57

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();
csonuryilmaz
  • 1,715
  • 24
  • 24
jmj
  • 237,923
  • 42
  • 401
  • 438
19
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();
bradwoo8621
  • 216
  • 1
  • 8