Close

Java Date Time - DayOfWeek.from() Examples

Java Date Time Java Java API 


Class:

java.time.DayOfWeek

java.lang.Objectjava.lang.Objectjava.lang.Enumjava.lang.Enumjava.lang.ComparableComparablejava.io.SerializableSerializablejava.time.DayOfWeekjava.time.DayOfWeekjava.time.temporal.TemporalAccessorTemporalAccessorjava.time.temporal.TemporalAdjusterTemporalAdjusterLogicBig

Method:

public static DayOfWeek from(TemporalAccessor temporal)

The static method DayOfWeek.from(TemporalAccessor temporal) obtains DayOfWeek enum based on the provided TemporalAccessor.

It attempts to extract the DAY_OF_WEEK field from the provided temporal accessor. If the provided temporal accessor doesn't support the field UnsupportedTemporalTypeException is thrown.


Examples


DayOfWeek.from method extracts the day of week field from LocaleDate.

package com.logicbig.example.dayofweek;

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

public class DayOfWeekFromExample {
public static void main (String[] args) {
DayOfWeek from = DayOfWeek.from(LocalDate.of(2005, 5, 20));
System.out.println(from);
}
}

Output

FRIDAY




This example attempts to extract DayOfWeek from MonthDay which doesn't support the DAY_OF_WEEK field so UnsupportedTemporalTypeException is thrown.

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

public class DayOfWeekFromExample2 {
public static void main (String[] args) {
MonthDay monthDay = MonthDay.of(5, 4);
boolean supported = monthDay.isSupported(ChronoField.DAY_OF_WEEK);
System.out.println(supported);
DayOfWeek dayOfWeek = DayOfWeek.from(monthDay);
System.out.println(dayOfWeek);
}
}

Output

Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfWeek
at java.time.temporal.TemporalAccessor.range(TemporalAccessor.java:174)
at java.time.MonthDay.range(MonthDay.java:386)
at java.time.MonthDay.get(MonthDay.java:417)
at java.time.DayOfWeek.from(DayOfWeek.java:192)
... 7 more




See Also