Time: How to get the next friday?

Viewed 42938

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.

Java 8 introduces java.time package (Tutorial) which is even better.

8 Answers

A simple modulo based solution which should work with most of former java versions in case you are not allowed to upgrade your java version to java8 or onwards or to use a standard java date library as jodatime

Number of days to add to your date is given by this formula :

(7 + Calendar.FRIDAY - yourDateAsCalendar.get(Calendar.DAY_OF_WEEK)) % 7

Note also this can be generalized for any week day by changing the static field Calendar.FRIDAY to your given weekday. Some snippet code below

public static void main(String[] args) {
    for (int i = 0; i < 15; i++) {

        Calendar cur = Calendar.getInstance();
        cur.add(Calendar.DAY_OF_MONTH, i);

        Calendar friday = Calendar.getInstance();
        friday.setTime(cur.getTime());
        friday.add(Calendar.DAY_OF_MONTH, (7 + Calendar.FRIDAY - cur.get(Calendar.DAY_OF_WEEK)) % 7);

        System.out.println(MessageFormat.format("Date {0} -> {1} ", cur.getTime(),  friday.getTime()));
    }
}

Here's an alternative way of doing it, without using any other classes/APIs outside LocalDate.

     LocalDate nextFriday = (d.plusWeeks(1).withDayOfWeek(5).minusDays(7).isAfter(d)) 
                            ? d.plusWeeks(1).withDayOfWeek(5)
                            : d.withDayOfWeek(5);
Related