迭代日期范围Java,奇怪的结果

时间:2013-06-11 10:17:47

标签: java date

我想在不使用库(即Joda)的情况下迭代日期范围。 我写了那个简单的代码,但结果很奇怪。例如,对于日期2010-01-01 2010-02-01,它打印:

1.0.2010
2.0.2010
3.0.2010
4.0.2010
5.0.2010
6.0.2010
7.0.2010
8.0.2010
9.0.2010
10.0.2010
11.0.2010
12.0.2010
13.0.2010
14.0.2010
15.0.2010
16.0.2010
17.0.2010
18.0.2010
19.0.2010
20.0.2010
21.0.2010
22.0.2010
23.0.2010
24.0.2010
25.0.2010
26.0.2010
27.0.2010
28.0.2010
29.0.2010
30.0.2010
31.0.2010
1.1.2010

日期也存在问题:2010-05-01 2010-06-01(打印4月而不是5月)。有什么帮助吗?

import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.text.DateFormatSymbols;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
import javax.swing.JOptionPane;
import java.util.GregorianCalendar;

class test
{
    public static void main(String[] args) {

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = null, endDate = null;

        try 
        {
            startDate = dateFormat.parse("2010-01-01"); // or 2010-05-01
            endDate = dateFormat.parse("2010-02-01"); // or 2010-06-01
        } 
        catch (ParseException pe) 
        {
            System.exit(-1);
        }

        Calendar start = Calendar.getInstance();
        start.setTime(startDate);
        Calendar end = Calendar.getInstance();
        end.setTime(endDate);

        for (Date date = start.getTime(); !start.after(end); start.add(Calendar.DATE, 1), date = start.getTime()) 
        {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            int day = cal.get(Calendar.DAY_OF_MONTH);
            int dow = cal.get(Calendar.DAY_OF_WEEK);  
            System.out.printf("%d.%d.%d\n", day, month, year);
        }
    }
}

1 个答案:

答案 0 :(得分:7)

库返回从0开始的月份.11

此外,您的循环可以简化。请注意,这可能不是最佳解决方案。

while(!start.after(end)) 
{
    int year = start.get(Calendar.YEAR);
    int month = start.get(Calendar.MONTH) + 1;
    int day = start.get(Calendar.DAY_OF_MONTH);
    System.out.printf("%d.%d.%d\n", day, month, year);        
    start.add(Calendar.DATE, 1);
}