flwy_h flwy_h - 3 months ago 9
Java Question

How do I increment calendar by 7 days until next month, then year from a starting date in Java?

This problem has been bugging me. I've googled around and found increment in java from current date but I want it starting from a certain date in the past.

For example, let's start with this date in this format:

"1986-09-20"

How can I increment the days so that the example above becomes "1986-09-27" and with one more increment it becomes "1986-10-4" all the way until the end of the year by which it becomes "1987-01-03"

I understand that I can just increment the date using += 7 on the day and if it surpasses say 30 then increment the month but I don't know how I can account for days that are either 30 or 31 or February's leap day.

I've been looking at the documentation for Calendar and notice that it may hold the solution but I don't know how/where to start.

I want to result format to be yyyy-mm-dd NOT the Java date format which is Day Month dd time time-zone yyyy

Answer

Is the following what you are looking for?

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1986, 8, 20);
int year = cal.get(Calendar.YEAR);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
while (year >= cal.get(Calendar.YEAR)) {
    cal.add(Calendar.DAY_OF_MONTH, 7);
    System.out.println(sdf.format(cal.getTime()));
}

the output:

1986-09-27
1986-10-04
1986-10-11
1986-10-18
1986-10-25
1986-11-01
1986-11-08
1986-11-15
1986-11-22
1986-11-29
1986-12-06
1986-12-13
1986-12-20
1986-12-27
1987-01-03

Comments