0

i have a method which has to print the next seven days but instead of printing next seven days it prints last seven days,

could some one help me fixing this please

here is the method i use,

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TestCalandar
{
    public static void main(String[] args)
    {
        SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");
        String date[] = null;
        date = df.format(new Date()).split("/");
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(date[2]), Integer.parseInt(date[0]) - 1, Integer.parseInt(date[1]));
        Map<String, String> currentWeekMap = new HashMap<String, String>();

        for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++)
        {
            cal.set(Calendar.DAY_OF_WEEK, i);
            currentWeekMap.put(dayFormat.format(cal.getTime()), df.format(cal.getTime()));
        }
        System.out.println(currentWeekMap);
    }
}
Joe
  • 4,460
  • 19
  • 60
  • 106
  • Use [LocalDate#plusDays](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#plusDays-long-) – Kachna Aug 14 '15 at 19:14
  • 1
    @Win.ubuntu Only a valid answer if running Java 8. – Andreas Aug 14 '15 at 19:20
  • 1
    possible duplicate of [How can I increment a date by one day in Java?](http://stackoverflow.com/questions/428918/how-can-i-increment-a-date-by-one-day-in-java) – ComputerDruid Aug 14 '15 at 19:43

5 Answers5

1

Use the new Java8 time API. This will accomplish what your code was trying to.

Map<String, String> currentWeekMap = new HashMap<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");

LocalDate today = LocalDate.now();
for (int i=1; i<=7; i++) {
    LocalDate newDay = today.plusDays(i);
    String dayOfWeek = newDay.getDayOfWeek().toString();
    String formattedDate = newDay.format(formatter);
    currentWeekMap.put(dayOfWeek, formattedDate);
}

System.out.println(currentWeekMap);
Andrew Mairose
  • 10,615
  • 12
  • 60
  • 102
0

The method Calendar.set sets the specified field, in this case the DAY_OF_WEEK field, to the specified value. The effect on the other fields is dependent on other factors, more specifically, the effect of Calendar.set is to change the day of week and the adjustment will happen within the current WEEK_OF_YEAR. This behavior is dependent on the locale that the code is running in.

Instead you, need to add a day, so you could use the Calendar.add method.

cal.set(Calendar.DAY_OF_WEEK, i)

could change to:

cal.add(Calendar.DAY_OF_YEAR, 1);

which will add one day to the day for every iteration of the loop.

If the output is required to be printed in order, then printing on each iteration of the loop would be better than putting into the HashMap, as HashMaps are not ordered.

Also, you state that your requirement is to print the next 7 days, so the first day should be tomorrow, which would mean that you can remove the following line. When you call Calendar.getInstance(), the date is automatically set to the current time in the current time zone, so you just want to start adding to the calendar from right now, which means the first date will be tomorrow.

cal.set(Integer.parseInt(date[2]), Integer.parseInt(date[0]) - 1, Integer.parseInt(date[1]));

See here: http://www.tutorialspoint.com/java/util/calendar_add.htm for the first search on Calendar.add in google.

Mike Curry
  • 1,609
  • 1
  • 9
  • 12
  • could you please give some example on this please – Joe Aug 14 '15 at 19:01
  • i get the following output which i think is not correct {Saturday=08/15/2015, Thursday=08/13/2015, Monday=08/10/2015, Tuesday=08/11/2015, Wednesday=08/12/2015, Friday=08/14/2015, Sunday=08/16/2015} – Joe Aug 14 '15 at 19:08
  • It is not order i am talking about, Please have a look at the values, it prints the past date not future date – Joe Aug 14 '15 at 19:24
0

I really short example

public class DateUtils {
    private DateUtils() {}

    public static Date addDays(Date baseDate, int daysToAdd) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(baseDate);
        calendar.add(Calendar.DAY_OF_YEAR, daysToAdd);
        return calendar.getTime();
    }
}
0

Here's the solution which should output what you want :). Hope it helps!

  import java.text.SimpleDateFormat;
  import java.util.Calendar;
  import java.util.Date;
  import java.util.HashMap;
  import java.util.Map;

  class TestCalandar
 {
     public static void main(String[] args){
     Calendar now = Calendar.getInstance();

     SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");

     String[] days = new String[7];
     int delta = now.get(Calendar.DAY_OF_WEEK)-6; 
     now.add(Calendar.DAY_OF_MONTH, delta );
     for (int i = 0; i < 7; i++)
     {
      days[i] = format.format(now.getTime());
       now.add(Calendar.DAY_OF_MONTH, 1);
     }
        for(int i = 0 ; i < days.length ; i++){
         System.out.println(days[i]);
   }

}

}
HenryDev
  • 4,685
  • 5
  • 27
  • 64
0

Here is the working one,

public static void main(String[] args) {
    SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");
    String date[] = null;
    date = df.format(new Date()).split("/");
    Calendar cal = Calendar.getInstance();
    cal.set(Integer.parseInt(date[2]), Integer.parseInt(date[0]), Integer.parseInt(date[1]));
    Map<String, String> currentWeekMap = new HashMap<String, String>();

    for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) {
        cal.add(Calendar.DATE, 1);
        currentWeekMap.put(dayFormat.format(cal.getTime()), df.format(cal.getTime()));
    }
    System.out.println(currentWeekMap);
}
Surya
  • 350
  • 2
  • 11