1. 程式人生 > >How to get the first date and last date of the previous month? (Java)

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

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.