我正在尝试编写一个简单的程序,该程序将自年初以来的每个第二个星期一(每个支付期日)添加到列表中,发生的事情有点奇怪,但我之前从未使用过 Calendar 类并且我想我可能错误地使用了 compareTo,但我阅读了 javadoc,看起来还可以。打包 javasampleapps;
导入 java.util.ArrayList;导入 java.util.Calendar;导入 java.util.Date;导入 java.util.GregorianCalendar;导入 java.util.HashMap;导入 java.util.List;导入 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);
}
}
}
它正在输出:
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
为什么要添加最后一个日期?9 月 26 日甚至还没有发生。