1

Hy, I wrote the code below and I don't understand why it's not working. For example for today (04.04.2020) dayOfWeek should be 7, but the result is 2….

    Calendar calendar = Calendar.getInstance();
    calendar.set(2020, 4, 4);
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
    System.out.println(dayOfWeek); //this print 2 on the console
mybrave
  • 1,662
  • 3
  • 20
  • 37
Ailema
  • 11
  • 3
  • I recommend you don’t use `Calendar`. That class is poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 05 '20 at 05:06

2 Answers2

2

The error is in this line of code:

calendar.set(2020, 4, 4);

It starts with January with the number 0. So the correct code would be:

calendar.set(2020, 3, 4);

Full code:

Calendar calendar = Calendar.getInstance();
calendar.set(2020, 3, 4);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek);

Outputs:

7
Kaimson
  • 166
  • 7
  • Thanks! Now I understand how it works! – Ailema Apr 04 '20 at 15:15
  • If you wanted to use the `Calendar` class (which we generally don’t), you should specify April using the named constant `Calendar.APRIL`, not the meaningless `3`. – Ole V.V. Apr 05 '20 at 05:33
  • I'm new in Java, I had an exercises as homework, was specified to use Calendar class, and I had as inputs numbers for moths and days. Thanks for the specifications, i will keep that in mind. – Ailema Apr 05 '20 at 09:47
  • @Ailema Thank you for the background. I find it awfully unfortunate that there are still teachers requiring students to use this and other classes that were replaced by far superior ones 6 years ago. – Ole V.V. Apr 05 '20 at 10:16
1

While @Kaimson's answer is correct, I would opt for using java8s LocalDate instead of java.util.Calendar, where you're code will be:

DayOfWeek.valueOf(LocalDate.now().getDayOfWeek()).name()

If you're not using java8, look into joda time, which has a similar API:

DateTime.now().dayOfWeek() // yields a number 1-7 representing the current day
hd1
  • 33,938
  • 5
  • 80
  • 91
  • Yeah, I've found a solution with LocalData class, but I wanted to understand why my first solution was not good. – Ailema Apr 04 '20 at 15:18
  • 1
    It's not good because the Calendar/Date library has many, many shortcomes, as adumbrated on the joda website. – hd1 Apr 04 '20 at 15:20
  • If using Java 6 or 7 and open to an external dependency, I’d clearly recommend [the backport of java.time](https://www.threeten.org/threetenbp/) over [Joda-Time](https://www.joda.org/joda-time/), though both are good options. – Ole V.V. Apr 05 '20 at 05:05