0

None of the existing threads helped me understand why the date that I enter in the main method (2016, 25, 11) which is a Friday is popping up as true for my method isWeekend(). I've seen in the other threads people talking about setting the Calendar's first day of week to Monday but I don't see how that would change my results

public static boolean isWeekend(Calendar userDate){
    if (userDate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || 
    userDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
        return true;
    else return false;
    } 

public static void main(String[] args) {
    Calendar c1 = Calendar.getInstance();
    c1.set(2016, 25, 11);
   System.out.println(CalendarBankHoliday.isWeekend(c1));
}  

Please can someone help me understand this

Edited: it correctly displays 2016,26,11 as a weekend(true) but 2016, 27, 11 as weekday(false)

Aidan Moore
  • 129
  • 1
  • 2
  • 6
  • It isn't a duplicate at all, the answer for my question is not the same as the one you've provided. Im asking for a boolean using Calendar static values not iterating through a week and skipping it if its saturday or sunday, the methods are completely different. – Aidan Moore Nov 26 '16 at 22:26

2 Answers2

3

Two things:

  1. The Calendar class works with 0-based months: January = 0, February = 1, etc.
  2. The set method takes the year, month, and day in that order, not year, day, and month.

The statement c1.set(2016, 25, 11); actually sets the date to February 11, 2018 (a Sunday), because 25 = 2×12 + 1, so the year is incremented by 2 and the month is set to February. Similarly, the statement c1.set(2016, 26, 11); actually sets the date to March 11, 2018 (also a Sunday).

To set c1 to November 25, 2016, change 11 to 10, and swap the second and third arguments:

c1.set(2016, 10, 25); // Friday, November 25, 2016

If you're hard-coding the date, you can also use a static constant for clarity:

c1.set(2016, Calendar.NOVEMBER, 25);
Michael Liu
  • 52,147
  • 13
  • 117
  • 150
2

I would advise against using the legacy Calendar and Date classes. In Java 8, there is a new package called java.time which has much nicer classes to deal with dates.

In your case, because it's just a date (without a time), java.time.LocalDate is appropriate for your use case. Nice easy methods to check days of the week, and it also attempts months so that January = 1.

Joe C
  • 15,324
  • 8
  • 38
  • 50