Java DayOfWeek Enum

The DayOfWeek is an immutable and thread-safe enum that represents 7 days of the week – Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.

How to use

The DayOfWeek enum provides access to the localized textual form of the day-of-week. The Java DayOfWeek enum can be used to represent a day-of-week, such as ‘Sunday’. Try the following examples to better understand –

Current day of week example

The following example program shows how you can use DayOfWeek enum with LocalDate to get the current day of the week.

import java.time.DayOfWeek;
import java.time.LocalDate;

public class DayOfWeekExample1 {

    public static void main(String[] args) {

        // Create instance of LocalDate from current date
        LocalDate localDate = LocalDate.now();

        // Get day of week from LocalDate
        DayOfWeek dayOfWeek = DayOfWeek.from(localDate);

        // Print it
        System.out.println(dayOfWeek);
    }
}

All months example

The following example program shows how you can use DayOfWeek enum to print all weekdays.

import java.time.DayOfWeek;

public class DayOfWeekExample2 {

    public static void main(String[] args) {

        // Get all the day of weeks
        DayOfWeek[] daysOfWeek = DayOfWeek.values();

        // Print them (SUNDAY, MONDAY etc..)
        for (DayOfWeek dayOfWeek : daysOfWeek) {
            System.out.println(dayOfWeek);
        }
    }
}

Weekday from weekday number example

The following example program shows how you can of() function to get weekday name from weekday number.

import java.time.DayOfWeek;

public class DayOfWeekExample3 {

    public static void main(String[] args) {

        // Get day of week from week-day-number
        DayOfWeek dayOfWeek = DayOfWeek.of(5);

        // 5th day of a week is FRIDAY
        System.out.println(dayOfWeek);
    }
}

Plus/minus example

The following example program shows how you can use plus/minus function to add or subtract days into the weekday

import java.time.DayOfWeek;

public class DayOfWeekExample4 {

    public static void main(String[] args) {

        // Get day of week from week-day-number
        DayOfWeek dayOfWeek = DayOfWeek.of(5);

        // 5th day of a week is FRIDAY
        System.out.println(dayOfWeek);

        // Add 2 days
        dayOfWeek = dayOfWeek.plus(2);

        // 7th day of a week is SUNDAY
        System.out.println(dayOfWeek);
    }
}