Ryan Hung
Ryan Hung

Reputation: 1

Calendar Java Program: How can I condense this code?

I am developing a method that returns an integer corresponding a day of the week of the first day in the year. Int 0 is Sunday, 1 is Monday, 2 is Tuesday, 3 is Wednesday... 6 is Saturday. Method header is as follows:

private static int firstDayOfYear (int year) 
{
}

My starting point is 2020, where the first day is a Wednesday on January 1, 2020. Therefore, 2019 would start on Tuesday, 2018 would start on Monday. 2021 would start on Thursday, and 2022 would start on Friday.

Currently, I have created this code inside the method. It works, but it feels clunky and I feel that there is a much efficient way to solve this problem. For now, my code calculates the distance from Wednesday and uses that to position what the Day of Week it is:

int difference = year - 2020;
int distance = difference % 7;

if (distance == -6)
return 4;
if (distance == -5)
return 5;
if (distance == -4)
return 6;
if (distance == -3)
return 0;
if (distance == -2)
return 1;
if (distance == -1)
return 2;
if (distance == 0)
return 3;
if (distance == 1)
return 4;
if (distance == 2)
return 5;
if (distance == 3)
return 6;
if (distance == 4)
return 0;
if (distance == 5)
return 1;
else
return 2;

If you've any suggestions on how to simplify or condense this code, I would greatly appreciate it.

Upvotes: 0

Views: 52

Answers (1)

JB Nizet
JB Nizet

Reputation: 691913

Don't reinvent the wheel. Use the JDK's java.time package classes

return LocalDate.of(year, 1, 1).getDayOfWeek().getValue() % 7

This is not only more concise and more readable. It's also more correct, since your code doesn't correctly deal with leap years.

Rather than using a non-standard, obscure conventions based on numbers, I would stick to using the DayOfWeek enum, though:

return LocalDate.of(year, 1, 1).getDayOfWeek()

Upvotes: 2

Related Questions