[英]How to find all valid dates between two dates in Java
I have 2 dates: 我有两个约会:
Calendar c1 = Calendar.getInstance();
c1.set(2014, 1, 1);
Calendar c2 = Calendar.getInstance();
c2.set(2013, 11, 1);
How can I get a list of all the valid dates in between (and including) these two dates? 如何获得这两个日期之间(包括两个日期)的所有有效日期的列表?
Start by determining which of the two dates is earlier. 首先确定两个日期中的哪个更早。 If c1
comes after c2
, swap the objects. 如果c1
在 c2
之后 ,则交换对象。
After that make a loop that prints the current date from c1
, and then calls c1.add(Calendar.DAY_OF_MONTH, 1)
. 之后,执行一个循环,从c1
打印当前日期,然后调用c1.add(Calendar.DAY_OF_MONTH, 1)
。 When c1
exceeds c2
, end the loop. 当c1
超过c2
,结束循环。
Here is a demo on ideone. 这是有关ideone的演示。 Note that month numbers are zero-based, so your example enumerates dates between Dec-1, 2013 and Feb-1, 2014, inclusive, and not between Nov-1, 2013 and Jan-1, 2014, as the numbers in the program might suggest. 请注意,月份数字是从零开始的,因此您的示例将枚举日期为2013年12月1日至2014年2月1日之间(包括两端),而不是2013年11月1日至2014年1月1日之间的日期作为程序中的数字可能会建议。
I would in general also recommend using joda-time , but here's a pure Java solution: 通常,我也建议使用joda-time ,但这是一个纯Java解决方案:
Calendar c1 = Calendar.getInstance();
c1.set(2013, 1, 1);
Calendar c2 = Calendar.getInstance();
c2.set(2014, 11, 1);
while (!c1.after(c2)) {
System.out.println(c1.getTime());
c1.add(Calendar.DAY_OF_YEAR, 1);
}
In essence: keep incrementing the earlier date until it falls after the later date. 本质上:不断增加较早的日期,直到它晚于较晚的日期为止。 If you want to keep them in an actual List<Calendar>
, you'll need to copy c1
on every iteration and add the copy to the list. 如果要将它们保留在实际的List<Calendar>
,则需要在每次迭代中复制c1
并将副本添加到列表中。
@Nonnull
public static List<Date> getDaysBetween(@Nonnull final Date start, @Nonnull final Date end)
{
final List<Date> dates = new ArrayList<Date>();
dates.add(start);
Date nextDay = dayAfter(start);
while (nextDay.compareTo(end) <= 0)
{
dates.add(nextDay);
}
return dates;
}
@Nonnull
public static Date dayAfter(final Date date)
{
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
gc.roll(Calendar.DAY_OF_YEAR, true);
return gc.getTime();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.