If using Java 8 (or higher), don't use Calendar
. If using Java 6 or 7, you might want to consider using the ThreeTen Backport. In either case, use the Java Time API.
Using Java Time
Since input is int year
and int month
, use YearMonth
.
To find last day number of month, call lengthOfMonth()
.
To get the date at the end of month, call atEndOfMonth()
.
Demo
int year = 2020;
int month = 2;
int lastDay = YearMonth.of(year, month).lengthOfMonth();
System.out.println(lastDay);
LocalDate date = YearMonth.of(year, month).atEndOfMonth();
System.out.println(date);
Output
29
2020-02-29
Using Joda-Time
If you don't have Java 8, and already use Joda-Time, do it this way:
Demo
int year = 2020;
int month = 2;
int lastDay = new LocalDate(year, month, 1).dayOfMonth().getMaximumValue();
System.out.println(lastDay);
LocalDate date = new LocalDate(year, month, 1).dayOfMonth().withMaximumValue();
System.out.println(date);
Output
29
2020-02-29
Using Calendar
If you insist on using Calendar
, call getActualMaximum(Calendar.DAY_OF_MONTH)
as also mentioned in other answers.
Since input is int year
and int month
, don't build and parse a string, just set Calendar
fields directly. Note that "month" in Calendar
is zero-based.
Demo
int year = 2020;
int month = 2;
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(year, month - 1, 1);
int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, lastDay);
Date date = calendar.getTime();
System.out.println(lastDay);
System.out.printf("%tF%n", date);
Output
29
2020-02-29