Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting next Monday using JodaTime

Tags:

jodatime

I am using JodaTime to figure out what the current LocalDate is and then getting the following Monday's date.

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

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

Why is my method not working in getting the following Monday when it is currently a Monday?

like image 875
The Nomad Avatar asked Aug 12 '14 05:08

The Nomad


1 Answers

Joda-Time does not offer a built-in elegant solution so you have to do your own 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 to 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 is my method not working in getting the following Monday when it is currently a Monday?

the answer is that the method withDayofWeek() sets the date to Monday in CURRENT week (which is dependent on the week model (ISO used in Joda-Time, but US-week differ in when a week starts for example - not supported by Joda-Time).

Note that with JSR-310 (not applicable to Android) or my library Time4J there is 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);
like image 58
Meno Hochschild Avatar answered Sep 27 '22 23:09

Meno Hochschild