I would like to know if there is an existing enum containing all the week days in Java. I'm using Calendar to treat time logic but I didn't see anything like this (I could create it myself but I 'd rather use something existing). I also saw the threeten project but it's still in alpha. Since an enum containing days of week is so trivial it's shown by sun in the enum documentation, I was thinking something may already exist. Any ideas ?
A day-of-week, such as 'Tuesday'. DayOfWeek is an enum representing the 7 days of the week - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. In addition to the textual enum name, each day-of-week has an int value. The int value follows the ISO-8601 standard, from 1 (Monday) to 7 (Sunday).
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
You want new DateFormatSymbols().getWeekdays()
.
The troublesome old date-time classes such as java.util.Calendar
are now legacy, supplanted by java.time classes.
java.time.DayOfWeek
enumJava now includes the java.time.DayOfWeek
enum.
Pass around objects of this enum rather than mere integers 1-7 to make your code more self-documenting, provide type-safety, and ensure a range of valid values.
invoices.printReportForDayOfWeek( DayOfWeek.MONDAY );
Numbering is 1-7 for Monday to Sunday, per ISO 8601 standard.
Get a localized name of the day by calling getDisplayName
.
String output = DayOfWeek.MONDAY.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Or Locale.US, etc.
To track multiple days of the week, use an EnumSet
(implementation of Set
) or EnumMap
(implementation of Map
).
Set<DayOfWeek> weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;
…
Boolean todayIsWeekend = weekend.contains( LocalDate.now( ZoneId.of( "America/Montreal" ) ).getDayOfWeek() );
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With