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.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(2020, 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(2021, 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 month’s length for the year of 2010 from January to December.

And here are the result of our code snippet above:

2021-11-16: 30

2020-02: 29

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.