How to find nearest week day for an arbitrary date?

Posted by Stig Brautaset on Stack Overflow See other posts from Stack Overflow or by Stig Brautaset
Published on 2011-11-30T05:26:50Z Indexed on 2011/12/01 1:54 UTC
Read the original article Hit count: 206

Filed under:
|

Is there a more elegant way than the below to find the nearest day of the week for a given date using JodaTime? I initially thought setCopy() would be it, but this sets the day to the particular day in the same week. Thus, if ld is 2011-11-27 and day is "Monday" the following function returns 2011-11-21, and not 2011-11-28 as I want.

    // Note that "day" can be _any_ day of the week, not just weekdays.
    LocalDate getNearestDayOfWeek(LocalDate ld, String day) {
        return ld.dayOfWeek().setCopy(day);
    }

Below is a work-around I came up with that works for the particular constraints in my current situation, but I'd love to get help find a completely generic solution that works always.

    LocalDate getNearestDayOfWeek(LocalDate ld, String day) {
        LocalDate target = ld.dayOfWeek().setCopy(day);
        if (ld.getDayOfWeek() > DateTimeConstants.SATURDAY) {
            target = target.plusWeeks(1);
        }
        return target;
    }

Looking more into this I came up with this, which seems to be a more correct solution, though it seems awfully complicated:

LocalDate getNearestDayOfWeek(LocalDate ld, String day) {
    LocalDate target = ld.dayOfWeek().setCopy(day);

    if (target.isBefore(ld)) {
        LocalDate nextTarget = target.plusWeeks(1);
        Duration sincePrevious = new Duration(target.toDateMidnight(), ld.toDateMidnight());
        Duration untilNext = new Duration(ld.toDateMidnight(), nextTarget.toDateMidnight());

        if (sincePrevious.isLongerThan(untilNext)) {
            target = nextTarget;
        }
    }
    return target;
}

© Stack Overflow or respective owner

Related posts about java

Related posts about jodatime