Search code examples
javaandroiddatecalendarsimpledateformat

How to get next seven days in android?


In my app, I need next seven days from the current day. I tried the following solution but it is skipping some days.

Calendar calendar = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
for (int i = 0; i < 7; i++) {
    calendar.add(Calendar.DATE, i);
    String day = sdf.format(calendar.getTime());
    Log.i(TAG, day);
}

I am getting the following output:

Sunday 18-Oct-2015
Monday 19-Oct-2015
Wednesday 21-Oct-2015
Saturday 24-Oct-2015
Wednesday 28-Oct-2015
Monday 02-Nov-2015
Sunday 08-Nov-2015

I also tried Calendar.DAY_OF_WEEK, Calendar.DAY_OF_MONTH, Calendar.DAY_OF_YEAR instead of Calendar.DATE but getting the same output.


Solution

  • Try this:

    SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
    for (int i = 0; i < 7; i++) {
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DATE, i);
        String day = sdf.format(calendar.getTime());
        Log.i(TAG, day);
    }
    

    You have one instance of calendar and are adding 1, 2, 3, 4, 5, 6, and 7 days to it without resetting it. The above solution moves object creation to be within the loop.