Days in month

This example will show how to find the total number of days in a month using java, java 8 and joda time. Each snippet will use the the month of April to find that it has 30 days in month.

Straight up Java

In this snippet will use java to find the maximum number of days in a month by calling Calendar getActualMaximum and passing the field number representing a month.

@Test
public void days_in_month_java() {

    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, 3);
    c.set(Calendar.DAY_OF_MONTH, 4);
    c.set(Calendar.YEAR, 2014);

    int numberOfDays = c.getActualMaximum(Calendar.DAY_OF_MONTH);

    assertEquals(30, numberOfDays);
}    

Java 8

Java 8 LocalDate lengthOfMonth method will return the the number of days in a month. In the snippet below, a date of April will return 30 days. Another way to find total number of days in a month would be to call LocalDate.getMonth() which will return the Month enum and then call the length which will return length of month in days.

@Test
public void days_in_month_java8() {

    LocalDate date = LocalDate.of(2014, Month.APRIL, 01);

    int length = date.getMonth().length(true);

    assertEquals(30, length);

    // or

    int length2 = date.lengthOfMonth();

    assertEquals(30, length2);
}

Joda Time

Using joda we can find the total number of days in a given month by calling the getMaximumValue method.

@Test
public void days_in_month_joda() {

    DateTime dateTime = new DateTime(2014, 4, 3, 0, 0, 0, 0);

    int daysInMonth = dateTime.dayOfMonth().getMaximumValue();

    assertEquals(30, daysInMonth);
}