Learn to determine which day of the week is a given date in Java. The weekdays are considered all 7 days 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
- This is an immutable and thread-safe enum.
2. Determining DayOfWeek from 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
LocalDate, other temporal classes also provide this method.
3. Localized Display
Use getDisplayName(TextStyle, Locale) to get the value of a day of the week in locale-specific manner.
DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek(); String displayName = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()); // Sunday String displayNameInGerman = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.GERMAN); // Sonntag
Happy Learning !!