Java DayOfWeek enum

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java DayOfWeek enum

In Java the DayOfWeek is an enum representing the 7 days of the week. In addition with the textual enum name, every day-of-week has an int value.


Java DayOfWeek enum declaration

Let's see the declaration of java.time.DayOfWeek.

  1. public enum DayOfWeek extends Enum implements TemporalAccessor, TemporalAdjuster  

Methods of Java DayOfWeek

Method

Description

int get(TemporalField field)

It is used to get the value of the specified field from this day-of-week as an int.

boolean isSupported(TemporalField field)

It is used to check if the specified field is supported.

DayOfWeek minus(long days)

It is used to return the day-of-week that is the specified number of days before this one.

DayOfWeek plus(long days)

It is used to return the day-of-week that is the specified number of days after this one.

static DayOfWeek of(int dayOfWeek)

It is used to obtain an instance of DayOfWeek from an int value.

static DayOfWeek[] values()

It is used to return an array containing the constants of this enum type, in the order they are declared.

Java DayOfWeek Example: get()

  1. import java.time.*;  
  2. import java.time.temporal.ChronoField;  
  3. public class DayOfWeekExample {  
  4.   public static void main(String[] args) {  
  5.     LocalDate localDate = LocalDate.of(2017, Month.JANUARY, 25);  
  6.     DayOfWeek dayOfWeek = DayOfWeek.from(localDate);  
  7.     System.out.println(dayOfWeek.get(ChronoField.DAY_OF_WEEK));  
  8.   }  
  9. }  

Output:

3

Java DayOfWeek Example: of()

  1. import java.time.DayOfWeek;  
  2. public class DayOfWeekExample {  
  3.   public static void main(String[] args) {  
  4.     DayOfWeek day = DayOfWeek.of(5);  
  5.     System.out.println(day.name());  
  6.     System.out.println(day.ordinal());  
  7.     System.out.println(day.getValue());  
  8.   }  
  9. }  

Output:

FRIDAY
4
5

Java DayOfWeek Example: plus()

  1. import java.time.*;  
  2. public class DayOfWeekExample {  
  3.   public static void main(String[] args) {  
  4.     LocalDate date = LocalDate.of(2017, Month.JANUARY, 31);  
  5.     DayOfWeek day = DayOfWeek.from(date);  
  6.     System.out.println(day.getValue());  
  7.     day = day.plus(3);  
  8.     System.out.println(day.getValue());  
  9.   }  
  10. }  

Output:

2
5

Java DayOfWeek Example: minus()

  1. import java.time.*;  
  2. public class DayOfWeekExample {  
  3.   public static void main(String[] args) {  
  4.     LocalDate date = LocalDate.of(2017, Month.JANUARY, 31);  
  5.     DayOfWeek day = DayOfWeek.from(date);  
  6.     System.out.println(day.getValue());  
  7.     day = day.minus(3);  
  8.     System.out.println(day.getValue());  
  9.   }  
  10. }  

Output:

2
6