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

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();


Use something like:

    Date date; // your date
    Calendar cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH);
    int day = cal.get(Calendar.DAY_OF_MONTH);
    // etc.

Beware, months start at 0, not 1.

Edit: Since Java 8 it’s better to use java.time.LocalDate rather than java.util.Calendar. See this answer for how to do it.



你的電子郵件位址並不會被公開。 必要欄位標記為 *