我想在两个特定日期之间进行迭代,并将所有相应的10分钟值存储在ArrayList中。我按照Get all full hours of every day of a year线程中的答案和代码示例进行了操作,但我在根据需要自定义代码时遇到了问题。到目前为止,我的代码如下:
final DateFormat df = DateFormat.getDateTimeInstance();
final Calendar c = Calendar.getInstance();
c.clear();
for (c.set(StringDateUtils.getYear(earliestKey), (StringDateUtils.getMonth(earliestKey) - 1),
StringDateUtils.getDayOfMonth(earliestKey), StringDateUtils.getHourOfDay(earliestKey),
StringDateUtils.getMinuteOfHour(earliestKey));
c.get(Calendar.YEAR) <= StringDateUtils.getYear(latestKey) &&
c.get(Calendar.MONTH) <= (StringDateUtils.getMonth(latestKey) - 1) &&
c.get(Calendar.DAY_OF_MONTH) <= StringDateUtils.getDayOfMonth(latestKey) &&
c.get(Calendar.HOUR) <= StringDateUtils.getHourOfDay(latestKey) &&
c.get(Calendar.MINUTE) <= StringDateUtils.getMinuteOfHour(latestKey);
c.add(Calendar.MINUTE, 10)) {
System.out.println(df.format(c.getTime()));
}
earliestKey 包含具有最早日期的字符串, latestKey 包含具有最新日期的字符串。 StringDateUtils是一个自定义编写的类,它包含从以YYYYMMDD_HHMM方式汇编的String获取年,月等的所有辅助方法。我还检查了 earliestKey 和 latestKey 的值,以上述形式有效,一切似乎都可以。正如我所理解的那样,问题在于循环条件的第二部分,即经典循环迭代中的问题是中断条件。 我试过'!='而不是不等式,或者代替AND运算符,但我无法让它工作。以下代码剪切不会进入第一次迭代。
答案 0 :(得分:2)
循环条件无效。与复合值进行比较时,只需在所有前面的值相等时比较二级值。
E.g。如果结束值为endA
,endB
和endC
,则条件应为:
a < endA || (a == endA && (b < endB || (b == endB && c <= endC)))
但是,为了获得更好的性能,您应该将结束条件解析为可以轻松测试的单个值:
final DateFormat df = DateFormat.getDateTimeInstance();
final Calendar c = Calendar.getInstance();
c.clear();
c.set(StringDateUtils.getYear(latestKey),
StringDateUtils.getMonth(latestKey) - 1,
StringDateUtils.getDayOfMonth(latestKey),
StringDateUtils.getHourOfDay(latestKey),
StringDateUtils.getMinuteOfHour(latestKey));
long endMillis = c.getTimeInMillis();
c.clear();
c.set(StringDateUtils.getYear(earliestKey),
StringDateUtils.getMonth(earliestKey) - 1,
StringDateUtils.getDayOfMonth(earliestKey),
StringDateUtils.getHourOfDay(earliestKey),
StringDateUtils.getMinuteOfHour(earliestKey));
for (; c.getTimeInMillis() <= endMillis; c.add(Calendar.MINUTE, 10))
System.out.println(df.format(c.getTime()));
现在,由于StringDateUtils
是一个自制的助手类,你应该添加一个帮助器来设置Calendar
,在这种情况下你最终会得到:
final DateFormat df = DateFormat.getDateTimeInstance();
final Calendar c = Calendar.getInstance();
StringDateUtils.clearAndSetYearToMinute(c, latestKey);
long endMillis = c.getTimeInMillis();
StringDateUtils.clearAndSetYearToMinute(c, earliestKey);
for (; c.getTimeInMillis() <= endMillis; c.add(Calendar.MINUTE, 10))
System.out.println(df.format(c.getTime()));
如果使用Java 8+,则应使用新的java.time
:
final DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
ZonedDateTime endDateTime = StringDateUtils.getZonedDateMinute(latestKey);
ZonedDateTime dateTime = StringDateUtils.getZonedDateMinute(earliestKey);
for (; ! dateTime.isAfter(endDateTime); dateTime = dateTime.plusMinutes(10)) {
System.out.println(dateTime.format(formatter));
}