Languages
[Edit]
EN

Java - get number of days in month

2 points
Created by:
Root-ssh
116210

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();
    }

    @Test
    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:

<!-- https://mvnrepository.com/artifact/org.assertj/assertj-core -->
<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.8.0</version>
    <scope>test</scope>
</dependency>

 

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.

❤️💻 🙂

Join