开发者

Help with java calendar logic

开发者 https://www.devze.com 2023-02-18 13:23 出处:网络
I am working with the Java Calendar class to do the following: Set a start date Set an end date Any date within that range is a \"valid\" date

I am working with the Java Calendar class to do the following:

  1. Set a start date
  2. Set an end date
  3. Any date within that range is a "valid" date

I have this somewhat working, and somewhat not. Please see the code below:

    nowCalendar.set(Calendar.DATE开发者_C百科, nowCalendar.get(Calendar.DATE) + offset);
    int nowDay = nowCalendar.get(Calendar.DATE);

    Calendar futureCalendar = Calendar.getInstance();
    futureCalendar.set(Calendar.DATE, nowDay + days);

    Date now = nowCalendar.getTime();
    Date endTime = futureCalendar.getTime();

    long now_ms = now.getTime();
    long endTime_ms = endTime.getTime();

    for (; now_ms < endTime_ms; now_ms += MILLIS_IN_DAY) {
        valid_days.addElement(new Date(now_ms));
        System.out.println("VALID DAY: " + new Date(now_ms));
    }

Basically, I set a "NOW" calendar and a "FUTURE" calendar, and then I compare the two calendars to find the valid days. On my calendar, valid days will be shaded white and invalid days will be shaded gray. You will notice two variables:

    offset = three days after the current selected date
    days = the number of valid days from the current selected date

This works...EXCEPT when the current selected date is the last day of the month, or two days prior (three all together). I think that its the offset that is definitely screwing it up, but the logic works everywhere else. Any ideas?


Don't fiddle with milliseconds. Clone the nowCalendar, add 1 day to it using Calendar#add() in a loop as long as it does not exceed futureCalendar and get the Date out of it using Calendar#getTime().

Calendar clone = nowCalendar.clone();

while (!clone.after(futureCalendar)) {
    validDays.add(clone.getTime());
    clone.add(Calendar.DATE, 1);
}

(note that I improved validDays to be a List instead of the legacy Vector)


Use add instead of set in the first line, otherwise the month is not adjusted if you are at the month boundary:

nowCalendar.add(Calendar.DATE, offset);


public boolean isInRange(Date d)
{
   Calendar cal = Calendar.getInstance();
   cal.setTime(d);
   return cal.after(startCal) && cal.before(endCal);
}

Here the startCal is the calendar instance of start time and endCal is end time.


I found the problem:

As soon as I set futureCalendar to be a clone of nowCalendar (plus the additional days), then it started working. Thanks for everyone's suggestions!

0

精彩评论

暂无评论...
验证码 换一张
取 消