Get first and last date of the previous month
43,485
Solution 1
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();
Solution 2
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();
Author by
Admin
Updated on September 19, 2020Comments
-
Admin over 3 years
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.