I had to ask for the last day of the month in Java, but I was surprised, so I made a note.
It is possible to use a date-based library, but it is possible by using the getActualMaximum () method of the java.util.Calender class as shown below.
test.java
//Find the last day of January 2019
int year = 2019;
int month = 1;
Calendar cal = Calendar.getInstance();
cal.clear();//Required in some cases
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month-1); //January is 0 for the month
int lastDayOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
When you first instantiate a calendar, getInstance () with no arguments will create an instance with the current date. If the method is called on the 31st, then the next time you set a month that has only 30 days, it will be strange. This can be avoided by calling clear () in advance.
In the Calrender class, Calendar.Month is the actual value of the month minus one. When setting the month, it is necessary to set a number that is one less than the actual number of months.
Recommended Posts