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.
counting bytes @fvu answer can be shortened even further to:
It's possible to do it in a much easier to read way:
or in a bit shorter form
or even shorter
PS. I didn't test the actual code! :)
I just wasted like 30 minutes trying to figure this out myself but I needed to generically roll forward.
Anyway here is my solution:
Now you just need to make a Partial (which LocalDate is) for the day of the week.
Now whatever the most significant field is of the partial will be +1 if the current date is after it (now).
That is if you make a partial with March 2012 it will create a new datetime of March 2013 or <.
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.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