6

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
ChrisAF
  • 63
  • 1
  • 3
  • 1
    The answer of WChargin is right. I'd just like to know why you want to do that. Using arrays is often a sign of bad object oriented design. Maybe your code could be refactored. If you would explain your goal for storing the weekdays in an array maybe we could find a better solution (or understand that your solution is the best) – Martin Mar 10 '13 at 18:17

4 Answers4

7

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)
wchargin
  • 15,589
  • 12
  • 71
  • 110
2

tl;dr

LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )
         .plusDays( 5 )
         .getDayOfWeek()
         .getDisplayName( TextStyle.FULL , Locale.US )

Details

Get your mind off the idea of array index relating to day-of-week.

Also, generally better to use a modern collection object to gather your objects rather than a mere array.

Also, avoid the troublesome Calendar class. Now supplanted by the java.time classes.

First get the current date. The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

We know the result for yesterday is yesterday so no need to calculate that date. If you do need the date, call LocalDate::minusDays.

We can ask each LocalDate for the name of its day by extracting a DayOfWeek enum object. That DayOfWeek know its own name in any human language that you can specify via a Locale object. So there is no need for you to track an array of template name-of-day strings. Tip: In OOP, try to think of either (a) letting objects be smart take care of themselves, or (b) enlisting the aid of a helper object, rather than using basic arrays to do all the work yourself.

List<String> dayNames = new ArrayList<>( 7 ) ;  // Initialize to seven days of a week.
dayNames.add( "yesterday" ) ;
dayNames.add( "today" ) ;
for( int i = 1 ; i <= 5 ; i ++ ) {
    LocalDate ld = today.plusDays( i ) ;
    String dayName = ld.getDayOfWeek().getDisplayName( TextStyle.FULL , Locale.US ) ;
    dayNames.add( dayName ) ;  // Add each of the five days remaining in a week.
}

Try this code live in IdeOne.com.

[yesterday, today, Tuesday, Wednesday, Thursday, Friday, Saturday]


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

You can use the remainder operator (%):

6 % 7 == 6
7 % 7 == 0
8 % 7 == 1
DanneJ
  • 358
  • 1
  • 9
-1
import java.text.SimpleDateFormat;
import java.util.*;
class Date {</p><br>
    public static void main(String args[]) { </p><br>
    // Monday 01/27/2019 15:07:53 AM
    System.out.println("Current Day: "+new SimpleDateFormat("EEEE MM-dd-yyyy HH:mm:ss a").format(Calendar.getInstance().getTime()) );
   }
}
kboul
  • 13,836
  • 5
  • 42
  • 53
  • This does not provide an answer to the question. You can [search for similar questions](//stackoverflow.com/search), or refer to the related and linked questions on the right-hand side of the page to find an answer. If you have a related but different question, [ask a new question](//stackoverflow.com/questions/ask), and include a link to this one to help provide context. See: [Ask questions, get answers, no distractions](//stackoverflow.com/tour) – Wayne Phipps Jan 27 '19 at 19:36
  • 1
    It seems to be answering a different question from the one asked here. – Ole V.V. Jan 27 '19 at 22:25