简体   繁体   English

遍历日期范围的Java,奇怪的结果

[英]Iterate through date range Java, strange results

I want to iterate through date ranges without using libraries (ie Joda). 我想遍历日期范围而不使用库(即Joda)。 I wrote that simple code but got strange results. 我写了那个简单的代码,但是得到了奇怪的结果。 For example, for dates 2010-01-01 2010-02-01 it prints: 例如,对于日期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

the problem exists also for dates: 2010-05-01 2010-06-01 (prints april instead of may). 日期也存在该问题:2010-05-01 2010-06-01(打印4月而不是5月)。 Any help? 有什么帮助吗?

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

Month that the library return start at 0 .. 11 库返回的月份开始于0 .. 11

Also your loop could be simplified liked this. 也可以简化您的循环,就像这样。 Note that this might not be the best solution. 请注意,这可能不是最佳解决方案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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