Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar - Get last day of previous month

Tags:

java

android

I want to get the last day of the previous month. But this doesnt seem to work:

Calendar cal = Calendar.getInstance();
Integer lastDay = cal.getInstance().getActualMaximum(cal.DAY_OF_MONTH);

cal.add(Calendar.MONTH, -1);

Integer prevMonth = cal.get(Calendar.MONTH);
Integer prevMonthYear = cal.get(Calendar.YEAR);
Integer lastDayPrevMonth = cal.getInstance().getActualMaximum(cal.DAY_OF_MONTH);

System.out.println("Previous month was: " + prevMonth + "-" + prevMonthYear);
System.out.println("Last day in previous month was: " + lastDayPrevMonth);
System.out.println("Last day in this month is: " + lastDay);

This outputs:

I/System.out﹕: Previous month was 10-2015
I/System.out﹕: Last day in previous month was 31
I/System.out﹕: Last day in this month is 31

So it's getting the previous month, that's november (10), giving that it is now december (11). Last day in this month is also correct, but clearly, last day in previous month was not 31, but 30.

Why does the second getActualMaximum give the same "last-day-in-month" as the first, when I do the add -1 thing?

like image 911
Simun Avatar asked Dec 03 '15 21:12

Simun


2 Answers

The problem in your current code is that you are calling multiple times the Calendar.getInstance() method, which returns the current date.

To obtain a Calendar which is the last day of the previous month, you can have the following:

public static void main(String... args) {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, -1);
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

    System.out.println(cal.get(Calendar.MONTH));
    System.out.println(cal.get(Calendar.DAY_OF_MONTH));
}

It subtracts one month from the current month and sets the day of month to its maximum value, obtained with getActualMaximum. Note that the month is 0-based in Calendar so January is actually 0.

like image 108
Tunaki Avatar answered Oct 10 '22 16:10

Tunaki


You can use LocalDate as below:

LocalDate.now().withDayOfMonth(1).minusDays(1)
like image 31
psg Avatar answered Oct 10 '22 17:10

psg