There is a much easier, buit-in way to get the day of the year for a given date, you have to be using Java 8, however. In order to use that, you must import java.time.LocalDate;
The following is the same method as in the code, however, it has been written using built-in way of obtaining the day of the year:
public static String getDay(int day, int month, int year) {
LocalDate date = LocalDate.of(year, month, day);
return date.getDayOfYear().name();
}
Despite of this, I thought it would be fun to make my own method, which uses Zeller's rule to calculate the day of the week for any given date.
Zeller's rule states:
where
- is the day of the week
- 0 → Sunday
- 1 → Monday
- 2 → Tuesday
- 3 → Wednesday
- 4 → Thursday
- 5 → Friday
- 6 → Saturday
- is the day of the month
- is the month of the year
- January → 11
- February → 12
- March → 1
- April → 2
- May → 3
- June → 4
- July → 5
- August → 6
- September → 7
- October → 8
- November → 9
- December → 10
- is the number of decades in the century up to the year (i.e. year % 100)
- is the number of centuries up to the century (i.e. year / 100)
For some dates, there are cases where evaluates to a negative number. The rule provides a work-around for such a case as follows: