6

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?

Torben
  • 3,805
  • 26
  • 31
The Nomad
  • 7,155
  • 14
  • 65
  • 100

2 Answers2

10

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);
Community
  • 1
  • 1
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
0

You could try

int targetDay = 1; //or DateTimeConstants.MONDAY
int nowDay = now.getDayOfWeek();

if (nowDay >= targetDay) return now.plusWeeks(1);
else return now.withDayOfWeek(targetDay);

//Or using ternary operator:
return (nowDay >= targetDay ? now.plusWeeks(1) : now).withDayOfWeek(targetDay)
Nicolai Weitkemper
  • 403
  • 1
  • 9
  • 18