Search code examples
androiddatetimedays

I am passing index for dates and not expected dates coming


In code the loop is to get me next week 7 days and add them to the array list. When I try this I get Mon, Tue, Thu, Sun, Thu, Tue .I don't understand why it is like that. It is not right one.

I need output as Mon, Tue, Web, Thus, Fri, Sat .

According to docs here , the numeric value for Monday is 1, Tuesday is 2 and so on.

   String dat,day;

    calendar = Calendar.getInstance();
    DateFormat sdf = new SimpleDateFormat("dd-MMM"); //Date and time

    DateFormat sdf_ = new SimpleDateFormat("EEE");
    Date date = new Date();


int i=0;

    while (i<7)
    {
         calendar.add(Calendar.DAY_OF_WEEK, i);
         dat = sdf.format(new Date(calendar.getTimeInMillis()));
         day = sdf_.format(new Date(calendar.getTimeInMillis()));

        mDate.add(dat);
        mDay.add(day);

         i++;

    }    
  
  

Solution

  • I think you should use 1 instead of i in calendar.add(Calendar.DAY_OF_WEEK, 1) since you are using the same instance of calendar.

    int i=0;
    
        while (i<7)
        {
             calendar.add(Calendar.DAY_OF_WEEK, 1);
             dat = sdf.format(new Date(calendar.getTimeInMillis()));
             day = sdf_.format(new Date(calendar.getTimeInMillis()));
    
            mDate.add(dat);
            mDay.add(day);
    
             i++;
    
        }