我需要一个遍历日期间隔的循环

时间:2010-01-15 19:27:11

标签: java algorithm date

我有开始日期和结束日期。我需要在这两个日期之间每天进行迭代。

最好的方法是什么?

我只能建议:

Date currentDate = new Date (startDate.getTime ());
while (true) {
   if (currentDate.getTime () >= endDate.getTime ())
      break;
   doSmth ();
   currentDate = new Date (currentDate.getTime () + MILLIS_PER_DAY);
}

4 个答案:

答案 0 :(得分:13)

准备好运行; - )

public static void main(String[] args) throws ParseException {
    GregorianCalendar gcal = new GregorianCalendar();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
    Date start = sdf.parse("2010.01.01");
    Date end = sdf.parse("2010.01.14");
    gcal.setTime(start);
    while (gcal.getTime().before(end)) {
        gcal.add(Calendar.DAY_OF_YEAR, 1);
        System.out.println( gcal.getTime().toString());
    }
}

答案 1 :(得分:6)

同意那些说使用Calendar对象的人。

如果您尝试使用Date对象并添加24小时,则可能会遇到意外麻烦。

这是你的谜语:一年中最长的月份是多少?你可能认为这个问题没有答案。七个月各有31天,所以长度都一样,对吧?那么,在美国这几乎是正确的,但在欧洲,这将是错误的!在欧洲,十月是最长的一个月。它有31天1小时,因为欧洲人将他们的时钟设定为10小时的夏令时1小时,使10月的一天持续25小时。 (美国人现在在11月开始DST,有30天,所以11月仍然比10月或12月更短。因此,这个谜语对美国人来说并不那么有趣。)

我曾经因为你正在尝试做的事情而遇到麻烦:我使用了一个Date对象并在循环中添加了24小时。只要我没有跨越夏令时间界限,它就会起作用。但是当我这样做的时候,突然间我跳过了一天或两天同一天,因为2009年3月8日午夜+ 24小时= 3月10日凌晨1点。放下时间,就像我一样,3月9日被神秘地跳过。同样是2009年11月1日午夜+ 11月1日晚上11点11点,我们两次打11月1日。

答案 2 :(得分:3)

如果要操作日期,请使用Calendar对象。

    Calendar c = Calendar.getInstance();
    // ... set the calendar time ...
    Date endDate = new Date();
    // ... set the endDate value ...

    while (c.getTime().before(endDate) {
       // do something
       c.add(Calendar.DAY_OF_WEEK, 1);
    }

或使用Joda Time

答案 3 :(得分:2)