views:

571

answers:

2

How can I get the next friday with the Joda-Time API.

The LocalDate of today is today. It looks to me you have to decide whever you are before or after the friday of the current week. See this method:

private LocalDate calcNextFriday(LocalDate d) {
 LocalDate friday = d.dayOfWeek().setCopy(5);
 if (d.isBefore(friday)) {
  return d.dayOfWeek().setCopy(5);
 } else {
  return d.plusWeeks(1).dayOfWeek().setCopy(5);
 }
}

Is it possible to do it shorter or with a oneliner?

PS: Please don't advise me using JDKs date/time stuff. Joda-Time is a much better API.

+5  A: 

It's possible to do it in a much easier to read way:

if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
    return d.withDayOfWeek(DateTimeConstans.FRIDAY));
} else if (d.getDayOfWeek() == DateTimeConstants.FRIDAY) {
    // almost useless branch, could be merged with the one above
    return d;
} else {
    return d.plusWeeks(1).withDayOfWeek(DateTimeConstans.FRIDAY));
}

or in a bit shorter form

private LocalDate calcNextFriday(LocalDate d) {    
    if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
     d = d.withDayOfWeek(DateTimeConstans.FRIDAY));
    } else {
     d = d.plusWeeks(1).withDayOfWeek(DateTimeConstans.FRIDAY));
    }    
    return d; // note that there's a possibility original object is returned
}

or even shorter

private LocalDate calcNextFriday(LocalDate d) {    
    if (d.getDayOfWeek() >= DateTimeConstants.FRIDAY) {
     d = d.plusWeeks(1);
    }    
    return d.withDayOfWeek(DateTimeConstans.FRIDAY));
}

PS. I didn't test the actual code! :)

Esko
+1  A: 

Your code in 1 line

private LocalDate calcNextFriday3(LocalDate d) {
    return d.isBefore(d.dayOfWeek().setCopy(5))?d.dayOfWeek().setCopy(5):d.plusWeeks(1).dayOfWeek().setCopy(5);
}

Alternative approach

private LocalDate calcNextDay(LocalDate d, int weekday) {
    return (d.getDayOfWeek() < weekday)?d.withDayOfWeek(weekday):d.plusWeeks(1).withDayOfWeek(weekday);
}


private LocalDate calcNextFriday2(LocalDate d) {
    return calcNextDay(d,DateTimeConstants.FRIDAY);
}

somewhat tested ;-)

fvu
Thanks for your answer. Your suggestion with the more general approach is nice. But the oneliner is awkward in term of readability.
michael.kebe
@michaelkebe you asked for a oneliner, I just provided one... ;-)
fvu