Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time: How to get the next friday?

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.

like image 307
michael.kebe Avatar asked Oct 28 '09 09:10

michael.kebe


People also ask

How do you get next Friday in Python?

On Friday, this code returns the same day. To get the next, use (3-today. weekday())%7+1 . Just the old x%n to ((x-1)%n)+1 conversion.

How do I set the previous date in Java?

time. LocalDate. Use LocalDate 's plusDays() and minusDays() method to get the next day and previous day, by adding and subtracting 1 from today.


2 Answers

java.time

With the java.time framework built into Java 8 and later (Tutorial) you can use TemporalAdjusters to get next or previous day-of-week.

private LocalDate calcNextFriday(LocalDate d) {   return d.with(TemporalAdjusters.next(DayOfWeek.FRIDAY)); } 
like image 164
michael.kebe Avatar answered Nov 03 '22 08:11

michael.kebe


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

if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {     return d.withDayOfWeek(DateTimeConstants.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(DateTimeConstants.FRIDAY)); } 

or in a bit shorter form

private LocalDate calcNextFriday(LocalDate d) {         if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {         d = d.withDayOfWeek(DateTimeConstants.FRIDAY));     } else {         d = d.plusWeeks(1).withDayOfWeek(DateTimeConstants.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(DateTimeConstants.FRIDAY); } 

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

like image 35
Esko Avatar answered Nov 03 '22 09:11

Esko