Is there an elegant way to find the nearest day of the week for a specific date using JodaTime? Initially, I thought it would be setCopy() , but it sets the day on the same day in the same week. So, if ld is 2011-11-27 and day is Monday, the next function returns 2011-11-21 , 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); }
Required output for various inputs:
2011-12-04, Monday => 2011-12-05 2011-12-04, Tuesday => 2011-12-06 2011-12-04, Wednesday => 2011-12-07 2011-12-04, Thursday => 2011-12-01 2011-12-04, Friday => 2011-12-02 2011-12-04, Saturday => 2011-12-03 2011-12-04, Sunday => 2011-12-04 2011-12-05, Monday => 2011-12-05 2011-12-05, Tuesday => 2011-12-06 2011-12-05, Wednesday => 2011-12-07 2011-12-05, Thursday => 2011-12-08 2011-12-05, Friday => 2011-12-02 2011-12-05, Saturday => 2011-12-03 2011-12-05, Sunday => 2011-12-04
Below is a description of the work that I came up with to work with specific limitations in my current situation, but I would really like to get help finding a completely general solution that always works.
LocalDate getNearestDayOfWeek(LocalDate ld, String day) { LocalDate target = ld.dayOfWeek().setCopy(day); if (ld.getDayOfWeek() > DateTimeConstants.SATURDAY) { target = target.plusWeeks(1); } return target; }