How do I get the length of month represented by a date object?

The following example show you how to get the length of a month represented by a java.time.LocalDate and a java.time.YearMonth objects. Both of these classes have a method called lengthOfMonth() that returns the length of month in days represented by those date objects.

package org.kodejava.example.datetime;

import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;

public class LengthOfMonth {
    public static void main(String[] args) {
        //
        // Get the length of month of the current date.
        //
        LocalDate date = LocalDate.now();
        System.out.printf("%s: %d%n%n", date, date.lengthOfMonth());

        //
        // Get the length of month of a year-month combination value
        // represented by the YearMonth object.
        //
        YearMonth yearMonth = YearMonth.of(2015, Month.FEBRUARY);
        System.out.printf("%s: %d%n%n", yearMonth, yearMonth.lengthOfMonth());

        //
        // Repeat a process the get the length of a month for one year
        // period.
        //
        for (int month = 1; month <= 12; month++) {
            yearMonth = YearMonth.of(2010, Month.of(month));
            System.out.printf("%s: %d%n", yearMonth, yearMonth.lengthOfMonth());
        }
    }
}    

The main() method above start by showing you how to get the month length of a LocalDate object. First we create a LocalDate object using the LocalDate.now() static factory method which return today’s date. And then we print out the length of month of today’s date on the following line.

The next snippet use the YearMonth class. We begin by creating a YearMonth object that represent the month of February 2015. We created it using the YearMonth.of() static factory method. We then print out the length of month for those year-month combination.

In the last lines of the example we create a for loop to get all months length for the year of 2010 from January to December.

And here are the result of our code snippet above:

2015-07-17: 31

2015-02: 28

2010-01: 31
2010-02: 28
2010-03: 31
2010-04: 30
2010-05: 31
2010-06: 30
2010-07: 31
2010-08: 31
2010-09: 30
2010-10: 31
2010-11: 30
2010-12: 31
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply