23

How do you find the number of days in a month in Java?

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
chetan
  • 3,175
  • 20
  • 72
  • 113

3 Answers3

39

Set the year and month on a Calendar object and then use getActualMaximum to return the last day:

calendar.getActualMaximum(Calendar.DAY_OF_MONTH) 
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
6

Since Java 8, a simple way would be:

int daysInCurrentMonth = java.time.LocalDate.now().lengthOfMonth();
Øyvind Mo
  • 1,197
  • 1
  • 8
  • 7
3

java.time.Month

Using the java.time classes, the java.time.Month enum in particular.

int days = Month.FEBRUARY.minLength();  // 28
int days = Month.FEBRUARY.maxLength();  // 29
int days = Month.FEBRUARY.length( boolean_consider_leap_year ); // TRUE → 29, FALSE → 28.

You can get the Month object for a month number, 1-12 meaning January-December.

int monthNumber = Month.FEBRUARY.getValue();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154