Getting next monday using JodaTime

I use JodaTime

to figure out what the current LocalDate

is and then get the next Monday date.

When I use the following method and the current day is Monday, instead of getting the next Monday, it gets the current day.

private LocalDate getNextMonday() {
    LocalDate date = LocalDate.now();
    date = date.plusWeeks(1);
    return date.withDayOfWeek(DateTimeConstants.MONDAY);
}

      

Why doesn't my method work in getting next Monday when it is currently Monday?

+3


source to share


1 answer


Joda-Time does not offer a built-in elegant solution, so you need to do your workaround like this:

LocalDate today = LocalDate.now();
int old = today.getDayOfWeek();
int monday = 1;

if (monday <= old) {
    monday += 7;
}
LocalDate next = today.plusDays(monday - old);
System.out.println("Next monday: " + next);

      

If you are only interested in setting up next Monday, the code can be simplified as follows:

LocalDate today = LocalDate.now();
int old = today.getDayOfWeek();
LocalDate next = today.plusDays(8 - old);

      

About your question -



Why isn't my method working the next Monday when it is currently Monday?

the answer is that the method withDayofWeek()

sets the date to Monday in the week CURRENT (which depends on the week model (ISO is used in Joda-Time, but in the US the week differs in that the week starts, for example Joda-Time is not supported).

Note that JSR-310 (not Android) or my Time4J library has a more modern approach - see this Time4J -code:

PlainDate nextMonday =
    SystemClock.inLocalView().today().with(
        PlainDate.DAY_OF_WEEK.setToNext(Weekday.MONDAY)
    );
System.out.println("Next monday: " + nextMonday);

      

+8


source







All Articles