What I am looking for is to create an array of the days of the week in java, starting from yesterday and go up to six days time as such
String daysWeek[] = { "Yesterday", "Today", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
The first two elements of the array I want to return as Yesterday and Today.
At first this seemed like an easy task by using
currentDay = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
String daysList[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
String daysWeek[] = {"Yesterday", "Today", daysList[currentDay], daysList[currentDay+1], ...};
A note on above daysList[currentDay]
will return tomorrow since the array of daysList
starts at 0 i.e if currentDay = 3
which says today is Tuesday then this will be daysList[2]
.
But my problem lies in that if the currentDay is 7 which implies today is Saturday then currentDay+1
which is tomorrow will be the eighth element of the array which doesn't exist.
Is there any which in I can loop round my numbers that if today is Wednesday or later then once currentDay + x > 7
, set currentDay
back to 1?
This all takes place in one method as is called getDaysList(currentDay)
which returns the daysWeek[]
array.
To get the day of the week, use Calendar. DAY_OF_WEEK.
DayOfWeek is an enum representing the 7 days of the week - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. In addition to the textual enum name, each day-of-week has an int value. The int value follows the ISO-8601 standard, from 1 (Monday) to 7 (Sunday).
String[] daysOfWeek = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”}; This creates an array that contains the seven string element representing days of the week within the curly braces. Note that we don't use the new keyword or specify the type of the array in this array literal syntax.
The now() method of LocalDate class The now() method of the Localdate class returns the Date object representing the current time.
A function of use to you here is the modulo (%
) operator.
Basically, what the modulo operator does is take the remainder of the division, which is exactly what you want. (Remember back in fourth grade when "9 / 2" wasn't 4.5, but 4 remainder 1? This is that remainder part.)
So instead of having:
days[currentDay + x]
Use:
days[(currentDay + x) % 7]
Quick example on values returned by the modulo operator:
0 % 7 = 0 (0 / 7 = 0 R0)
1 % 7 = 1 (1 / 7 = 0 R1)
6 % 7 = 6 (6 / 7 = 0 R6)
7 % 7 = 0 (7 / 7 = 1 R0)
8 % 7 = 1 (8 / 7 = 1 R1)
15 % 7 = 1 (15 / 7 = 2 R1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With