سؤال

I'm trying to write a simple procedure that will add to a List every second Monday (every pay period day) since the beginning of the year, what is happening is kind of strange but I've never worked with the Calendar class before and I think I may be using compareTo incorrectly but I read the javadoc and it seems okay. package javasampleapps;

import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map;

/**
 *
 * @author DavidH
 */
public class AddingDaysToCalendar {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Calendar cal = new GregorianCalendar();
        System.out.println(cal.get(Calendar.WEEK_OF_YEAR));
        cal.add(Calendar.WEEK_OF_YEAR, 1);
        System.out.println(cal.get(Calendar.WEEK_OF_YEAR));

        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.WEEK_OF_YEAR, 1 + 1);

        Calendar currentDate = new GregorianCalendar();
        currentDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        int counter = 2;
        List<Date> dates = new ArrayList<Date>();
        while ((cal.getTime().compareTo((currentDate.getTime())) < 0)) {
            cal.set(Calendar.WEEK_OF_YEAR, counter);
            dates.add(cal.getTime());
            counter += 2;
        }
        System.out.println("Listing Dates:");
        for (Date d : dates) {
            System.out.println(d);
        }
    }
}

It is outputting this:

39
40
Listing Dates:
Mon Jan 03 13:37:29 AST 2011
Mon Jan 17 13:37:29 AST 2011
Mon Jan 31 13:37:29 AST 2011
Mon Feb 14 13:37:29 AST 2011
Mon Feb 28 13:37:29 AST 2011
Mon Mar 14 13:37:29 ADT 2011
Mon Mar 28 13:37:29 ADT 2011
Mon Apr 11 13:37:29 ADT 2011
Mon Apr 25 13:37:29 ADT 2011
Mon May 09 13:37:29 ADT 2011
Mon May 23 13:37:29 ADT 2011
Mon Jun 06 13:37:29 ADT 2011
Mon Jun 20 13:37:29 ADT 2011
Mon Jul 04 13:37:29 ADT 2011
Mon Jul 18 13:37:29 ADT 2011
Mon Aug 01 13:37:29 ADT 2011
Mon Aug 15 13:37:29 ADT 2011
Mon Aug 29 13:37:29 ADT 2011
Mon Sep 12 13:37:29 ADT 2011
Mon Sep 26 13:37:29 ADT 2011

Why is it adding the very last date? Sep 26th hasn't even occurred yet.

هل كانت مفيدة؟

المحلول

Why is it adding the very last date? Sep 26th hasn't even occurred yet.

Because you advance the date after you check its relation to the current time, and before you add it to the list:

 while ((cal.getTime().compareTo((currentDate.getTime())) < 0)) {
     cal.set(Calendar.WEEK_OF_YEAR, counter);
     dates.add(cal.getTime());
     counter += 2;
 }

This should fix that problem (may introduce others though):

 while ((cal.getTime().compareTo((currentDate.getTime())) < 0)) {
     dates.add(cal.getTime());
     counter += 2;
     cal.set(Calendar.WEEK_OF_YEAR, counter);
 }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top