Rom*_*man 7 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);
}
Run Code Online (Sandbox Code Playgroud)
sta*_*ker 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());
}
}
Run Code Online (Sandbox Code Playgroud)
同意那些说使用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日.