How do I get number of each day for a certain month in Java?

You can get the number of each day (Monday, Tuesday, etc.) for a specific month in Java using the java.time package introduced in Java 8. In the following code snippet we will use a loop to iterate the dates in the month. The number of loop is equals to the number of days in the month.

You can run this code to get the count of each day of the week for any specific month and year. Here’s a sample code to achieve that:

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.EnumMap;
import java.util.Map;

public class DaysOfWeekInMonthWithLoop {

    public static Map<DayOfWeek, Integer> getDaysCountForMonth(int year, int month) {
        YearMonth yearMonth = YearMonth.of(year, month);
        LocalDate firstOfMonth = yearMonth.atDay(1);
        LocalDate lastOfMonth = yearMonth.atEndOfMonth();

        Map<DayOfWeek, Integer> daysCount = new EnumMap<>(DayOfWeek.class);

        for (DayOfWeek day : DayOfWeek.values()) {
            daysCount.put(day, 0);
        }

        for (LocalDate date = firstOfMonth; !date.isAfter(lastOfMonth); date = date.plusDays(1)) {
            DayOfWeek dayOfWeek = date.getDayOfWeek();
            daysCount.put(dayOfWeek, daysCount.get(dayOfWeek) + 1);
        }

        return daysCount;
    }

    public static void main(String[] args) {
        int year = 2024;
        int month = 10; // October

        Map<DayOfWeek, Integer> daysCount = getDaysCountForMonth(year, month);

        for (Map.Entry<DayOfWeek, Integer> entry : daysCount.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output:

MONDAY: 4
TUESDAY: 5
WEDNESDAY: 5
THURSDAY: 5
FRIDAY: 4
SATURDAY: 4
SUNDAY: 4

What we do in the code snippet above:

  1. YearMonth: Used to represent the year and month. You create an instance of YearMonth for the desired year and month.
  2. LocalDate: Represents a date (year, month, day). firstOfMonth is the first day of the month and lastOfMonth is the last day of the month.
  3. EnumMap: A specialized map for use with enum keys, which in this case are days of the week (from DayOfWeek enum).
  4. Loop through Dates: Iterate from the first to the last day of the month. For each date, get the day of the week and update the count in the map.

Another solution that we can use is to calculate the number of days using a simple mathematical calculations instead of iterating through the dates of the month.

The refined approach:

  1. Determine the first day of the month.
  2. Calculate the base number of times each day appears:
    • Each day will appear at least daysInMonth / 7 times because every 7-day week will have each day once.
    • The remainder from daysInMonth % 7 will determine how many days are left over from complete weeks, starting from the first day of the month.

Here is how we can implement it:

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.EnumMap;
import java.util.Map;

public class DaysOfWeekInMonth {

    public static Map<DayOfWeek, Integer> getDaysCountForMonth(int year, int month) {
        YearMonth yearMonth = YearMonth.of(year, month);
        LocalDate firstDayOfMonth = yearMonth.atDay(1);

        int daysInMonth = yearMonth.lengthOfMonth();
        DayOfWeek firstDayOfWeek = firstDayOfMonth.getDayOfWeek();

        Map<DayOfWeek, Integer> daysCount = new EnumMap<>(DayOfWeek.class);

        int baseCount = daysInMonth / 7;
        int extraDays = daysInMonth % 7;

        for (DayOfWeek day : DayOfWeek.values()) {
            daysCount.put(day, baseCount);
        }

        for (int i = 0; i < extraDays; i++) {
            DayOfWeek currentDay = firstDayOfWeek.plus(i);
            daysCount.put(currentDay, daysCount.get(currentDay) + 1);
        }

        return daysCount;
    }

    public static void main(String[] args) {
        int year = 2024;
        int month = 10; // October

        Map<DayOfWeek, Integer> daysCount = getDaysCountForMonth(year, month);

        for (Map.Entry<DayOfWeek, Integer> entry : daysCount.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output:

MONDAY: 4
TUESDAY: 5
WEDNESDAY: 5
THURSDAY: 5
FRIDAY: 4
SATURDAY: 4
SUNDAY: 4

In this approach:

  1. YearMonth: Represents the year and month.
  2. LocalDate: Determines the first day of the month.
  3. DayOfWeek: Identifies the day of the week for the first day of the month.
  4. EnumMap: Stores the count of each day of the week.
  5. Base Count and Remainder:
    • baseCount: Calculates how many whole weeks (7 days) fit in the month.
    • extraDays: Calculates the remaining days after accounting for whole weeks.
    • Initialize each count in the map to baseCount.
    • Add 1 to the first extraDays days in the week starting from firstDayOfWeek.

This approach avoids explicitly iterating over each day in the month and relies on mathematical operations to determine the count of each day of the week.

How do I use the java.time.DayOfWeek enum?

The java.time.DayOfWeek enums in Java 8 Date-Time API describes the days of the week. The enum has constants value from DayOfWeek.MONDAY through DayOfWeek.SUNDAY. These enums also have their integer values where 1 is equal to MONDAY and 7 is equal to SUNDAY.

In the code snippet below you can see a couple usage of the DayOfWeek enums. We start by getting all the enum values using the values() method that return an array of DayOfWeek. We iterate this array and print out the enum value and its corresponding integer value.

// Get DayOfWeek enums value
DayOfWeek[] dayOfWeeks = DayOfWeek.values();
for (int i = 0; i < dayOfWeeks.length; i++) {
    DayOfWeek dayOfWeek = dayOfWeeks[i];
    System.out.println("dayOfWeek[" + i + "] = " + dayOfWeek + "; value = " +
            dayOfWeek.getValue());
}

To create a DayOfWeek object we can use the of(int) factory method. We pass an integer value of this method. For example giving 1 will give us the DayOfWeek.MONDAY. We can also utilize enum valueOf(String) method to create enum from string value.

// Get DayOfWeek from int value
DayOfWeek dayOfWeek = DayOfWeek.of(1);
System.out.println("dayOfWeek = " + dayOfWeek);

// Get DayOfWeek from string value
dayOfWeek = DayOfWeek.valueOf("SATURDAY");
System.out.println("dayOfWeek = " + dayOfWeek);

To get the DayOfWeek from a date-time object we can use the getDayOfWeek() method. Below we get the day of week from a LocalDate object.

// Get DayOfWeek of a date object
LocalDate date = LocalDate.now();
DayOfWeek dow = date.getDayOfWeek();

System.out.println("Date  = " + date);
System.out.println("Dow   = " + dow + "; value = " + dow.getValue());

We can also get the day of week for a specific locale. To do this we can use the DayOfWeek.getDisplayName(TextStyle, Locale) method. The TextStyle can be of value TextStyle.FULL, TextStyle.SHORT, TextStyle.NARROW which will give us the full, short, and narrow version of the display name. The example below get the display name for Indonesian and German version.

// Get DayOfWeek display name in different locale.
Locale locale = new Locale("id", "ID");
String indonesian = dow.getDisplayName(TextStyle.SHORT, locale);
System.out.println("ID = " + indonesian);

String germany = dow.getDisplayName(TextStyle.FULL, Locale.GERMANY);
System.out.println("DE = " + germany);

There is also a plus(long) method that can be used to add number of days to a DayOfWeek object. For example adding 4 to MONDAY will give us DayOfWeek.FRIDAY.

// Adding number of days to DayOfWeek enum.
System.out.println("DayOfWeek.MONDAY.plus(4) = " + DayOfWeek.MONDAY.plus(4));

Here is the complete code for the snippets above:

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;

public class DayOffWeekExample {
    public static void main(String[] args) {
        // Get DayOfWeek enums value
        DayOfWeek[] dayOfWeeks = DayOfWeek.values();
        for (int i = 0; i < dayOfWeeks.length; i++) {
            DayOfWeek dayOfWeek = dayOfWeeks[i];
            System.out.println("dayOfWeek[" + i + "] = " + dayOfWeek + "; value = " +
                    dayOfWeek.getValue());
        }

        // Get DayOfWeek from int value
        DayOfWeek dayOfWeek = DayOfWeek.of(1);
        System.out.println("dayOfWeek = " + dayOfWeek);

        // Get DayOfWeek from string value
        dayOfWeek = DayOfWeek.valueOf("SATURDAY");
        System.out.println("dayOfWeek = " + dayOfWeek);

        // Get DayOfWeek of a date object
        LocalDate date = LocalDate.now();
        DayOfWeek dow = date.getDayOfWeek();

        System.out.println("Date  = " + date);
        System.out.println("Dow   = " + dow + "; value = " + dow.getValue());

        // Get DayOfWeek display name in different locale.
        Locale locale = new Locale("id", "ID");
        String indonesian = dow.getDisplayName(TextStyle.SHORT, locale);
        System.out.println("ID = " + indonesian);

        String germany = dow.getDisplayName(TextStyle.FULL, Locale.GERMANY);
        System.out.println("DE = " + germany);

        // Adding number of days to DayOfWeek enum.
        System.out.println("DayOfWeek.MONDAY.plus(4) = " + DayOfWeek.MONDAY.plus(4));
    }
}

And the result of the code above are:

dayOfWeek[0] = MONDAY; value = 1
dayOfWeek[1] = TUESDAY; value = 2
dayOfWeek[2] = WEDNESDAY; value = 3
dayOfWeek[3] = THURSDAY; value = 4
dayOfWeek[4] = FRIDAY; value = 5
dayOfWeek[5] = SATURDAY; value = 6
dayOfWeek[6] = SUNDAY; value = 7
dayOfWeek = MONDAY
dayOfWeek = SATURDAY
Date  = 2021-11-16
Dow   = TUESDAY; value = 2
ID = Sel
DE = Dienstag
DayOfWeek.MONDAY.plus(4) = FRIDAY