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();
    cal.setTime(date);
    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.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *