我需要一个迭代日期间隔的循环

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

最好的方法是什么?

我只能建议:

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

准备好运行;-)

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

同意那些说使用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日午夜+ 24小时= 11月1日晚11点,我们两次打11月1日。

如果要操作日期,请使用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

我强烈建议使用Joda时间 :

Java Joda Time – 实现Date范围迭代器