Using numeric literals instead of Month or DayOfWeek enum constants when working with Java’s java.time API reduces code readability and can lead to errors.

Why is this an issue?

The java.time API introduced in Java 8 provides two convenient enums: Month for months of the year and DayOfWeek for days of the week. These enums make code more readable and self-documenting compared to numeric literals.

When you write LocalDate.of(2024, 1, 15), it’s not immediately clear whether the month parameter is zero-indexed (like the old Calendar API) or one-indexed. A reader must either memorize the API or look it up. In contrast, LocalDate.of(2024, Month.JANUARY, 15) is unambiguous and instantly understandable.

How to fix it

Replace numeric literals in your code with their corresponding java.time.Month or java.time.DayOfWeek enum constants when creating or manipulating dates. Most factory methods in the java.time API have overloads that accept enums instead of integers.

Use the following mapping to update your values:

Value Month DayOfWeek

1

Month.JANUARY

DayOfWeek.MONDAY

2

Month.FEBRUARY

DayOfWeek.TUESDAY

3

Month.MARCH

DayOfWeek.WEDNESDAY

4

Month.APRIL

DayOfWeek.THURSDAY

5

Month.MAY

DayOfWeek.FRIDAY

6

Month.JUNE

DayOfWeek.SATURDAY

7

Month.JULY

DayOfWeek.SUNDAY

8

Month.AUGUST

-

9

Month.SEPTEMBER

-

10

Month.OCTOBER

-

11

Month.NOVEMBER

-

12

Month.DECEMBER

-

Code examples

Noncompliant code example

LocalDate date = LocalDate.of(2024, 1, 15); // Noncompliant; "1" is used to represent January
YearMonth yearMonth = YearMonth.of(2024, 6); // Noncompliant; "6" is used to represent June
LocalDate date = LocalDate.now(ZoneOffset.UTC);
if (date.getMonthValue() == 9) { // Noncompliant; "9" is used to represent September
    // Handle September
}
DayOfWeek today = LocalDate.now(ZoneId.of("Europe/Paris")).getDayOfWeek();
boolean isWeekend = today.getValue() == 6 || today.getValue() == 7; // Noncompliant; "6" and "7" are used to represent Saturday and Sunday

Compliant solution

LocalDate date = LocalDate.of(2024, Month.JANUARY, 15);
YearMonth yearMonth = YearMonth.of(2024, Month.JUNE);
LocalDate date = LocalDate.now(ZoneOffset.UTC);
if (date.getMonth() == Month.SEPTEMBER) {
    // Handle September
}
DayOfWeek today = LocalDate.now(ZoneId.of("Europe/Paris")).getDayOfWeek();
boolean isWeekend = today == DayOfWeek.SATURDAY || today == DayOfWeek.SUNDAY;

Resources

Documentation