-3

On HackerRank doing Java challenges, I am supposed to get the day that corresponds to August 5, 2015. But I am getting Saturday instead of Wednesday. I tested putting 6 instead of 5, and I get Sunday instead of Thursday.

SusanW
  • 1,550
  • 1
  • 12
  • 22
Mark
  • 11
  • 1

3 Answers3

1

I can't really tell without code, but try changing the 8 to a 7.

If you are using the java.util.Calendar class, and its friends, then months start at 0, not 1, so 8 means September. The 5th Sept 2015 was a Saturday.

Why does it start from 0? That's because it's a very old part of the Java API, and back in the early/mid-1990s it was considered important for the API to be familiar to C programmers, and the C ctime library works that way.

Why did the ctime library work that way? Now we're into rumour and speculation, but it is easy to see how you might have an array of months, and want to use the month number as an index. For more speculation, see: Why is January month 0 in Java Calendar?

Final note: if you are using Java8, look at the new time and date library, derived from the very popular Joda time library by Stephen Colebourne (@JodaStephen). It's vastly more capable, pretty much free of silly problems like this, and rather learned in the area of date/time programming - a job well done!

Community
  • 1
  • 1
SusanW
  • 1,550
  • 1
  • 12
  • 22
1

I guess you are setting month to September. In Java months start from zero, so August is 7 actually, 8 is September. You can use the following code.

Calendar calendar = new GregorianCalendar(2015, 7, 5);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
taner
  • 83
  • 5
1

Calendar uses the following numeric values to denote the day.

SUNDAY=1, MONDAY=2, TUESDAY=3, WEDNESDAY=4, THURSDAY=5, FRIDAY=6 and SATURDAY = 7

San
  • 11
  • 2