I want a custom calendar like this:
enum TradingDays {Monday, Tuesday, Wednesday, Thursday, Friday};
Then I need to iterate over it and check if a particular enum element is the day of week TODAY. The problem is that the JAVA calendar does not match to days of week from my calendar. So:
Calendar now = Calendar.getInstance();
TradingDays.Monday is not equal to any of now.get(Calendar.DAY_OF_WEEK);
So how do I assign Monday, Tuesday etc from my calendar TradingDays the same type (in this case an integer value) from the JAVA calendar?
P.S. I need to have that calendar TradingDays like that because it is then shown to the user so he/she chooses on which days to trade.
Create a constructor inside your enum which takes an int value:
public class CalendarMain {
}
tl;dr
Details
This functionality is built into Java.
java.time.DayOfWeek
enumJava 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.
Numbering is 1-7 for Monday to Sunday, per ISO 8601 standard.
Get a localized name of the day by calling
getDisplayName
.Collection of day-of-week objects
To track multiple days of the week, use an
EnumSet
(implementation ofSet
) orEnumMap
(implementation ofMap
).Or in the case of this Question specifically, a collection of the weekdays. Perhaps define as a static final constant if the definition does not change during execution of the app.
Or make that even shorter by defining an EnumSet as a range of enum objects defined in a sequential order. Specify MONDAY & FRIDAY and let
EnumSet
fill in the values in between. UseEnumSet.range
.Then test for today. Note that a time zone is crucial in determining the current date. For any given moment the date varies around the globe by zone.
About java.time
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.You can try using a constructor inside your enum, like in this example:
While iterating you can use coin.value like this:
Which output is:
With
enum
s you can do a lot of things that probably are familiar to you:File
TradingDays.java
: