Get last day of Month in java

Get last day of month in java

Learn about how to get last day of month in java.
There are times when you need to get last day of month to process data at the end of each month.
For example: Processing salaries of the employee in your company.

There are multiple ways to get last day of month in java

Ways to get last day of month in java

Using LocalDate to get last day of month in Java 8

Here are the steps to get last day of month using LocalDate

  • Create new LocalDate object either by using LocalDate.now() or using given date.
  • Get Month object by calling LocalDate's getMonth() method.
  • Use Month's length() method get number of days in the month.
  • Finally, use LocalDate's WithDayOfMonth() method to get LocalDate from given day of the month.

Output:

Last date of the month: 2022-02-28
Last date of the month for date 13/01/2022: 2022-01-31

Using Calendar to get last day of month in java

Here are the steps to get last day of month using Calendar class.

  • Get Calendar obj using Calendar.getInstance()
  • Get lastDayOfMonth using Calendar's getActualMaximum() based on Calendar.Date
  • Set lastDateOfMonth to Calendar.Date
  • Extract all relevant informations such Last day of month or Day of week from Calendar object.

Output:

Last date of month: Mon Feb 28 18:43:05 IST 2022
Last day of month: 28
Day of week in Number: 2
Day of week in text:Monday
======================================
Last date of month: Tue Jan 31 00:00:00 IST 2012
Last day of month: 31
Day of week in Number: 3
Day of week in text:Thursday

Get last day of previous month in java

You need to subtract -1 from Calendar.Month and use getActualMaximum() to get last of previous month in java.

Here is complete example

Output:

Last date of previous month: Fri Dec 31 00:00:00 IST 2021

Get last day of next month in java

You need to add 1 from Calendar.Month and use getActualMaximum() to get last of next month in java.

Here is complete example

Output:

Last date of next month: Mon Feb 28 00:00:00 IST 2022

That’s all about how to get last day of month in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *