BAEL-6595 code for the How Many Days Are There in a Particular Month of a Given Year article

This commit is contained in:
thibault.faure 2023-06-01 23:54:00 +02:00
parent dfa2ef7a8e
commit 12de8904ab
2 changed files with 46 additions and 0 deletions

View File

@ -0,0 +1,21 @@
package com.baeldung.daysinmonth;
import java.time.YearMonth;
import java.util.Calendar;
public class DaysInMonthUtils {
public int getDaysInMonthWithYearOfMonth(int month, int year) {
YearMonth yearMonth = YearMonth.of(year, month);
return yearMonth.lengthOfMonth();
}
public int getDaysInMonthWithCalendar(int month, int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
return calendar.getActualMaximum(Calendar.DATE);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.daysinmonth;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class DaysInMonthUtilsUnitTest {
@Test
void whenGetDaysInMonthWithYearOfMonth_thenCorrectResult() {
assertEquals(31, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(3, 2024));
assertEquals(30, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(11, 1999));
assertEquals(28, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(2, 2025));
assertEquals(29, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(2, 2004));
}
@Test
void whenGetDaysInMonthWithCalendar_thenCorrectResult() {
assertEquals(31, new DaysInMonthUtils().getDaysInMonthWithCalendar(3, 2024));
assertEquals(30, new DaysInMonthUtils().getDaysInMonthWithCalendar(11, 1999));
assertEquals(28, new DaysInMonthUtils().getDaysInMonthWithCalendar(2, 2025));
assertEquals(29, new DaysInMonthUtils().getDaysInMonthWithCalendar(2, 2004));
}
}