Search code examples
javaandroiderror-handlingcalendardayofweek

Check if DAY_OF_WEEK is between Monday and Friday


I'm trying to create a method which is checking if "today" is between Monday and Friday. For this I get with this line 'int day = Calendar.DAY_OF_WEEK;' the actual day. After that I fill a ArrayList with the days (Monday, Tuesday, Wendsday, Thursday and Friday). Now when I check if the actual day is in my ArrayList, i set boolean DAY = true else i set boolean DAY = false. I tryed the Method today and yesterday, but it allways sets the boolean to false.

What do I need to change that my code works? You'll find the code down here.

Code

                int day = Calendar.DAY_OF_WEEK;
                ArrayList<Integer> daylist = new ArrayList<Integer>();
                daylist.add(Calendar.MONDAY);
                daylist.add(Calendar.TUESDAY);
                daylist.add(Calendar.WEDNESDAY);
                daylist.add(Calendar.THURSDAY);
                daylist.add(Calendar.FRIDAY);

                if (daylist.contains(day)){
                    DAY = true;
                }else{
                    DAY = false;
                }

Solution

  • Wow, that's like trying to kill a mosquito with a thermo-nuclear warhead :-)

    Java guarantees (in 1.5) (unchanged up to 1.8 at least) that the values of SUNDAY through SATURDAY are contiguous (1 through 7) so it's a simple matter of checking a range.

    However, DAY_OF_WEEK is not the day of the week, it's a field number (with the value 7) to be passed to the getter to retrieve the day of the week. The only time Calendar.DAY_OF_WEEK itself will match an actual day will be on Saturdays.

    You can use code such as:

    Calendar myDate = Calendar.getInstance(); // set this up however you need it.
    int dow = myDate.get (Calendar.DAY_OF_WEEK);
    boolean isWeekday = ((dow >= Calendar.MONDAY) && (dow <= Calendar.FRIDAY));
    

    Following this, isWeekday will be true if and only if the day from myDate was Monday through Friday inclusive.