3

I have a Gregorian Date and I want to get it's day of week. I have try this but get wrong answer:

Calendar calendar = new GregorianCalendar();

calendar.set(myYear, myMonth, myDay);

int result = calendar.get(Calendar.DAY_OF_WEEK);
switch (result) {
case Calendar.SUNDAY:
    Log.i("DayOfWeek", "SUN");
    break;

.
.
.

default:
    startDay = 0;
    break;
} 

What is problem?

Mohammad H
  • 785
  • 2
  • 10
  • 25
  • 3
    Did you use the month from 0..11 (correct) or 1..12 (incorrect)? – Maarten Bodewes Apr 26 '15 at 19:49
  • As @MaartenBodewes says, month, for whatever bizarre reason is zero indexed. I've run your code with a zero indexed month and it works. – Robert Bain Apr 26 '15 at 19:50
  • 3
    If you say you get wrong answer you must explain what is correct answer and what you get – michaldo Apr 26 '15 at 19:53
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html) / `GregorianCalendar`, and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 22 '18 at 20:43

1 Answers1

1

Finally I found the problem! The above code is correct but you should pass the standard month value (0 ... 11) instead of (1 ... 12) :

Calendar calendar = new GregorianCalendar();

calendar.set(myYear, myMonth-1, myDay);

int result = calendar.get(Calendar.DAY_OF_WEEK);
switch (result) {
case Calendar.SUNDAY:
    Log.i("DayOfWeek", "SUN");
    break;

.
.
.

default:
    startDay = 0;
    break;
}
Mohammad H
  • 785
  • 2
  • 10
  • 25
  • Glad you got it working, but I'm closing it as a dupe. This pitfall has been collecting unsuspecting programmers since it was introduced - I remember a long time ago I had to find my climbing gear as well ... :) – Maarten Bodewes Apr 26 '15 at 20:49
  • PS use the new Date / Time API (since Java 8). – Maarten Bodewes Apr 26 '15 at 20:50
  • @MaartenBodewes Would you like me to delete this post? Is there any problem with deleting posts ? – Mohammad H May 23 '17 at 07:45
  • No, there is no problem, but there is no direct need either. It has got upvotes so somebody liked it. Maybe it has got some keywords that Google picks up, who knows. Just leave it as a pointer to the question previously asked. You may have to delete the answer before the question if you go that way. – Maarten Bodewes May 23 '17 at 07:58