Java DayOfWeek explanation with example

Java DayOfWeek explanation with example :

DayOfWeek is an enum in Java that represents all seven days of a week. It is defined as :

public enum DayOfWeek

The name of the enum values are Monday,Tuesday, Wednesday, Thursday,Friday, Saturday and Sunday. Each name also has one integer value. The values are from 1(for Monday) to 7(for Sunday). One thing we should keep in mind that these values may not same for all Local ,the integer value may differ. The integer values follows ISO-8601 standard. So, it can be used in any application that supports ISO calendar system.

Let me show you few useful methods of DayOfWeek enum :

Print all the values of DayOfWeek :

Using values() method, we can get an array containing all values of DayOfWeek in the same order they are declared. We can iterate through them and print out the values :

import java.time.DayOfWeek;

class Main {
    public static void main(String args[]) {
        for (DayOfWeek d : DayOfWeek.values())
            System.out.println(d);
    }
}

It will print out the following output :

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

Get the integer values :

We can use getValue() method to print out the integer values associated with each week value. Like below :

import java.time.DayOfWeek;

class Main {
    public static void main(String args[]) {
        for (DayOfWeek d : DayOfWeek.values())
            System.out.println(d.getValue());
    }
}

Output :

1
2
3
4
5
6
7

Display day of week in user’s local and print in different form :

Using getDisplayName(TextStyle, Locale) method, we can get the string in user’s local. Also, we can pass FULL,NARROW or SHORT as the first argument to print the output in different form. Example :

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

class Main {
    public static void main(String args[]) {
        System.out.println(DayOfWeek.MONDAY.getDisplayName(TextStyle.FULL, Locale.getDefault()));
        System.out.println(DayOfWeek.MONDAY.getDisplayName(TextStyle.NARROW, Locale.getDefault()));
        System.out.println(DayOfWeek.MONDAY.getDisplayName(TextStyle.SHORT, Locale.getDefault()));
    }
}

Output :

Monday
M
Mon

Adding and removing day count to a value :

We can use plus(long days) and minus(long days) methods to add or subtract any amount of days from a day.

 import java.time.DayOfWeek;

class Main {
    public static void main(String args[]) {
        System.out.println(DayOfWeek.WEDNESDAY.plus(2));
        System.out.println(DayOfWeek.WEDNESDAY.minus(2));
    }
}

It will give the following output :

FRIDAY
MONDAY

Leave a Reply