Close

Java Date Time - DayOfWeek Examples

Java Date Time Java 


Enum DayOfWeek represents days of the week. It doesn't implement Temporal interface so it's not temporal-based. It doesn't represent a point on a timeline. It implements TemporalAccessor and TemporalAdjuster.


Examples


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

public class DayOfWeekExample {
public static void main (String[] args) {
//using a day
DayOfWeek d = DayOfWeek.SATURDAY;
System.out.println(d);
System.out.println(d.getValue());
System.out.println(d.getDisplayName(TextStyle.FULL, Locale.FRANCE));
//there's no method DayOfWeek.now()
// because it's not temporal-based


//subtracting
DayOfWeek d2 = d.minus(2);
System.out.println(d2);
//adding
DayOfWeek d3 = d.plus(2);
System.out.println(d3);

//from an int value 1 to 7
System.out.printf("Day starts from %s and ends with %s%n",
DayOfWeek.of(1),
DayOfWeek.of(7));
}
}

Output

SATURDAY
6
samedi
THURSDAY
MONDAY
Day starts from MONDAY and ends with SUNDAY




Getting DayOfWeek from other Temporal objects.

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoField;

public class DayOfWeekFromOtherDates {
public static void main (String[] args) {
DayOfWeek d = LocalDate.now().getDayOfWeek();
System.out.println(d);

int i = LocalDate.of(1999, 12, 31).get(ChronoField.DAY_OF_WEEK);
System.out.println(i);

DayOfWeek d2 = DayOfWeek.of(i);
System.out.println(d2);

/* similarly we can use other temporal objects:
LocalDateTime#getDayOfWeek();
ZonedDateTime#getDayOfWeek(); etc*/
}
}

Output

MONDAY
5
FRIDAY




See Also