In Java, there are multiple ways to get the last day of the month. Here are the ways that I found the easiest.
Using LocalDate
In Java 8, date and time have been revamped. It is recommended to manipulate date and time using all classes provided from the java.time package. We will use LocalDate class and TemporalAdjusters.lastDayOfMonth() to get the last day of the month.
import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; public class LastDayOfMonthLocalDate { public static void main(String[] args) { // Set a date, e.g. 2013-01-17. LocalDate anyDate = LocalDate.of(2013, 1, 17); // Get the last day of the month. LocalDate lastDayOfMonth = anyDate.with(TemporalAdjusters.lastDayOfMonth()); // Display. System.out.println(lastDayOfMonth); } }
Output
2013-01-31
Using Calendar
For Java 7 and below, use the getActualMaximum() function of the Calendar class. It returns the maximum value that the specified calendar field could have. For our purpose, we will use the Calendar.DAY_OF_MONTH field.
import java.text.SimpleDateFormat; import java.util.Calendar; public class LastDayOfMonthCalendar { public static void main(String[] args) { // Set a date, e.g. 2013-01-17. Calendar anyDate = Calendar.getInstance(); anyDate.set(2013, 0, 17); // Note: Month 0 is January. // Get the last day of the month. int lastDayOfMonth = anyDate.getActualMaximum(Calendar.DAY_OF_MONTH); anyDate.set(Calendar.DAY_OF_MONTH, lastDayOfMonth); // SimpleDateFormat is used because // Calendar.toString() outputs more data than needed. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(sdf.format(anyDate.getTime())); } }
Output
2013-01-31
Github
- For Java 8 and above: https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/time/LastDayOfMonthLocalDate.java
- For Java 7 and below: https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/time/LastDayOfMonthCalendar.java