使用 while 循环检查日期是否在 ArrayList 中的两个日期之间



我有以下while循环:

while (!inputDateCalendar.after(endYearCalendar) && !vacations.contains(newLesson.getDate())) {
    // Do stuff
}

inputDateCalendarendYearCalendar都是GregorianCalendar型。 vacations 是一个包含 Vacation 类型的项的ArrayList

public Vacation(String type, String region, Date startDate, Date endDate, int schoolYear)
{
    this.type = type;
    this.region = region;
    this.startDate = startDate;
    this.endDate = endDate;
    this.schoolYear = schoolYear;
}

newLesson是一个Lesson对象:

public class Lesson {
    private int id;
    private int studentID;
    private String student;
    private String type;
    private Time duration;
    private double price;
    private Date date;
    private Time time;
}

所有这些都已设置好。

现在我试图确保循环只做一些事情,而inputDateCalendar不在endYearCalendar之后,并且vacations不包含列表中任何VacationstartDateendDate之间的日期。

我知道人们会推荐Joda-time,但我现在想尝试一下。

正如 Mou 所指出的,您似乎遇到了一些类型问题 - 我认为您必须遍历假期列表并检查日期:

while(!inputDateCalendar.after(endYearCalendar)) {
    for(Vacation vacation : vacations) {
        if(newLesson.getDate().after(vacation.getStartDate()) && newLesson.getDate().before(vacation.getEndDate()))
            do.stuff();
    }
}

您可以用户Collections2.filter像这样的东西应该可以完成工作。

private static class LessonPredicate implements Predicate<Vacation> {
    private Lesson lesson;
    public LessonPredicate(Lesson lesson) {
        this.lesson = lesson;
    }
    @Override
    public boolean apply(Vacation vacation) {
        return lesson.getDate().after(vacation.getStartDate()) && lesson.getDate().before(vacation.getEndDate())
    }
}
while(!inputDateCalendar.after(endYearCalendar) && !Collections2.filter(vacations, new LessonPredicate(newLesson)).isEmpty()) {
    do.stuff();
}

最新更新