简体   繁体   中英

Using Calendar in while-loop?

The code below does what I want except for the very last output.

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()));
    }

Here is 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

I'm going to use this while loop to execute irreversible code and I want it to be when the year is NOT 1987. However, the 1987 shows up here and I've tried modifying the while loop condition to get the LAST entry to be

1986-12-27

but to no avail.

The desired output is the same as the output above except without the 1987 date.

Your loop is performing the add after it's performing the check. So you probably just want:

while (year >= cal.get(Calendar.YEAR)) {
    System.out.println(sdf.format(cal.getTime()));
    cal.add(Calendar.DAY_OF_MONTH, 7);
}

That will change the first value used, however - so you may want an extra add call before the start of the loop, if you want the same first value that you're printing at the moment.

The java.time (Java 8) alternative:

for(LocalDate date = LocalDate.of(1986, 9, 27);
        date.getYear() < 1987;
        date = date.plusWeeks(1)) {
    System.out.println(DateTimeFormatter.ISO_DATE.format(date));
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM