Java example to determine which day of the week is a given date. The weekdays are from Sunday, Monday till Saturday.
1. DayOfWeek Enum
DayOfWeek
is an enum representing the seven days of the week – Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.
As it is an enum, it has ordinal values associated with each day. It is from 1 (Monday) to 7 (Sunday). Some locales also assign different numeric values to the days, declaring Sunday to have the value 1, however, this class provides no support for this.
To get the numeric representation, use of getValue()
is recommended. This is an immutable and thread-safe enum.
2. DayOfWeek for given LocalDate
LocalDate
class has method getDayOfWeek() which return the enum value representing that day of the week.
LocalDate today = LocalDate.now(); System.out.println( today.getDayOfWeek() ); // SUNDAY System.out.println( today.getDayOfWeek().getValue() ); // 7
Similar to LocalDate
, other temporal classes also provide this method.
- LocalDate getDayOfWeek()
- LocalDateTime getDayOfWeek()
- ZonedDateTime getDayOfWeek()
3. Locale specific value
Use getDisplayName(TextStyle, Locale) to get the value of day of the week in locale specific manner.
public static void main(String[] args) { String textValue = getDayString(today, Locale.getDefault()); System.out.println(textValue); // Sunday textValue = getDayString(today, Locale.GERMAN); System.out.println(textValue); // Sonntag } public static String getDayString(LocalDate date, Locale locale) { DayOfWeek day = date.getDayOfWeek(); return day.getDisplayName(TextStyle.FULL, locale); }
Drop me your questions related to getting the day of the week in Java 8.
Happy Learning !!