问题
I need to check if a date(in string) exists in array list.
I have two dates, first i need to generate date ranges between these two dates and store them in an Array. This is what I am doing.
DateTimeFormatter dateFromatter= DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime startDate= formatter.parseDateTime("01/02/2012");
DateTime endDate= formatter.parseDateTime("01/31/2012");
List<LocalDate> dates = new ArrayList<LocalDate>();
int days = Days.daysBetween(startDate, endDate).getDays();
for (int i=0; i < days; i++) {
This is where i am getting problem.
Type mismatch: cannot convert from DateTime to LocalDate
> LocalDate listOfDates =
> startDate.withFieldAdded(DurationFieldType.days(), i);
> dates.add(listOfDates);
}
回答1:
Use org.joda.time.Interval
Interval interval = new Interval(startDate, endDate);
for (LocalDate date : dates)
{
if (interval.contains(date))
//
回答2:
Doesn't toLocalDate() work?
LocalDate listOfDates =
startDate.withFieldAdded(DurationFieldType.days(), i).toLocalDate();
Anyway, do you really need to generate each date? Unless I really need to, I would just do something similar to this:
Interval interval = new Interval(startDate.withTimeAsStartOfDay(),
endDate.withTimeAsStartOfDay().plusDays(1));
boolean isInInterval = interval.contains(date.withTimeAsStartOfDay());
回答3:
I came here looking for this, but neither solutions were acceptable to me - I ended up with the following:
int days = Days.daysBetween(startDate, endDate).getDays();
for(int i = 0; i <= days; i++) {
dates.add(startDate.plusDays(i));
}
Bear in mind that LocalDates are immutable so you're not actually changing it when you call plusDays(...). Also notice that I use <= to include the final day (in your example this would be 31st January).
来源:https://stackoverflow.com/questions/9313151/generate-date-ranges-in-jodatime