Java - get number of days in month

2 points
Created by:

Quick solution:

import org.junit.Test;
import java.time.YearMonth;
import static org.assertj.core.api.Assertions.assertThat;

public class MonthUtil {

    public static int getMaxDaysInMonth(int year, int month) {
        YearMonth yearMonthObject = YearMonth.of(year, month);
        return yearMonthObject.lengthOfMonth();

    public void test() {
            int year = 2021;
            int month = 7;
            int maxDaysInMonth = getMaxDaysInMonth(year, month);
            System.out.println(maxDaysInMonth); // 31

        assertThat(getMaxDaysInMonth(2021, 1)).isEqualTo(31);
        assertThat(getMaxDaysInMonth(2021, 2)).isEqualTo(28);
        assertThat(getMaxDaysInMonth(2021, 3)).isEqualTo(31);
        assertThat(getMaxDaysInMonth(2021, 4)).isEqualTo(30);
        assertThat(getMaxDaysInMonth(2021, 5)).isEqualTo(31);
        assertThat(getMaxDaysInMonth(2021, 6)).isEqualTo(30);
        assertThat(getMaxDaysInMonth(2021, 7)).isEqualTo(31);
        assertThat(getMaxDaysInMonth(2021, 8)).isEqualTo(31);
        assertThat(getMaxDaysInMonth(2021, 9)).isEqualTo(30);
        assertThat(getMaxDaysInMonth(2021, 10)).isEqualTo(31);
        assertThat(getMaxDaysInMonth(2021, 11)).isEqualTo(30);
        assertThat(getMaxDaysInMonth(2021, 12)).isEqualTo(31);

Lib for assertions - Assertions:

<!-- -->


Alternative titles

  1. get number of days in month java
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂