Getting a little stuck on the last day of the month using Java's Calendar class

What I wanted to do

I built a program that automatically converts February 31st to 28th when getting the last day of the month using Java's Calendar class. However, 31st was output even though February was specified.

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR,2019);
cal.set(Calendar.MONTH,2);

cal.getActualMaximum(Calendar.DATE);//The result is 31

Cause

The cause was that the Calendar class treated 0 as January, so when 2 was specified, it was treated as March.

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR,2019);
cal.set(Calendar.MONTH,1);//February

cal.getActualMaximum(Calendar.DATE)//The result is 28

Why don't you treat 1 as January ... I made a note for those who have the same eyes

Recommended Posts

Getting a little stuck on the last day of the month using Java's Calendar class
Output of the day of the week using Ruby's Date class
When using the constructor of Java's Date class, the date advances by 1900.
[Ruby] Display today's day of the week using Date class
How to derive the last day of the month in Java
Create a calendar from the Calendar class by specifying the year and month
[Java] How to get to the front of a specific string using the String class
Display Japanese calendar and days of the week using java8 standard class
A note on the libGDX Utils class
Reading a file using Java's Scanner class
A quick note on using jshell with the official Docker image of the JDK
[Ubuntu 20.04] Display the day of the week on the date / clock
I tried to decorate the simple calendar a little
Limit the number of threads using Java's Executor Service
Try using the query attribute of Ruby on Rails