Calendar - Get the last day of the previous month

I want to get the last day of the previous month. But this does not 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); 

It is output:

 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 

Thus, he receives the previous month, this November (10), giving him now December (11). The last day of this month is also correct, but obviously the last day of the previous month was not 31, but 30.

Why getActualMaximum second getActualMaximum give the same โ€œlast day of the monthโ€ as the first when I add the -1 item?

+6
source share
3 answers

The problem with your current code is that you call Calendar.getInstance() several times, which returns the current date.

To get Calendar , which is the last day of the previous month, you can get 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 the month to the maximum value obtained using getActualMaximum . Note that the month is 0 in Calendar , so January is actually 0.

+4
source

Try it, I think this will solve your problem:

 /** * Returns previous month date in string format * @param date * @return */ private static String getPreviousMonthDate(Date date){ final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy"); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.DAY_OF_MONTH, 1); cal.add(Calendar.DATE, -1); Date preMonthDate = cal.getTime(); return format.format(preMonthDate); } /** * Returns previous to previous month date in string format * @param date * @return */ private static String getPreToPreMonthDate(Date date){ final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy"); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MONTH, -1); cal.set(Calendar.DAY_OF_MONTH,1); cal.add(Calendar.DATE, -1); Date preToPreMonthDate = cal.getTime(); return format.format(preToPreMonthDate); } 
+1
source

You can use LocalDate as shown below: LocalDate.now (). WithDayOfMonth (1) .minusDays (1)

0
source

All Articles