0

I have using ThreeTen in android for displaying 1-week dates from the current date. However, the problem is dates are not displaying in the correct order.

Here's my code for days 1 week dates from the current date:

public List<LocalDate> getWeekDays() {

    ZoneId z = ZoneId.of("Pacific/Auckland");  // Or ZoneId.of( "Africa/Tunis" )
    LocalDate today = LocalDate.now( z ) ;

   LocalDate localDate = today.with( org.threeten.bp.temporal.TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY ) ) ;     
    List< LocalDate > dates = new ArrayList<>( 7 ) ;
    for( int i = 0 ; i < 7 ; i ++ ) {
        localDate = localDate.plusDays( i ) ;
        dates.add( localDate ) ;
    }
        return dates;

}

Here is the picture of displaying dates please check it:

enter image description here

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Lets Explorer
  • 123
  • 1
  • 2
  • 13

1 Answers1

3

Logic flaw in for loop

You are adding days to the previous date, not to your start date.

In your loop i runs through values 0 through 6. You start out from Sunday, October 21. First time through your loop you add 0 days, so still have October 21 (correct). Next time you add 1 day, get Oct. 22, also correct for Monday. Next time you add 2 days and get Oct. 24. Then you add 3 days, 4 days, etc. This explains your results.

Two possible fixes. Change this:

    localDate = localDate.plusDays( i ) ;
    dates.add( localDate ) ;

…to either this:

    LocalDate ld = localDate.plusDays( i ) ;  // Add `i` number of days to the *start* date, not the incrementing date. 
    dates.add( ld ) ;

or this:

    dates.add( localDate ) ;
    localDate = localDate.plusDays( 1 ) ; // only add 1 day to previous date

In the first case it is probably best if you change the localDate variable name to startDate for clarity.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161