Time: How to get the next friday?
Solution 1
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));
}
Solution 2
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! :)
Solution 3
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 ;-)
Solution 4
I just wasted like 30 minutes trying to figure this out myself but I needed to generically roll forward.
Anyway here is my solution:
public static DateTime rollForwardWith(ReadableInstant now, AbstractPartial lp) {
DateTime dt = lp.toDateTime(now);
while (dt.isBefore(now)) {
dt = dt.withFieldAdded(lp.getFieldTypes()[0].getRangeDurationType(), 1);
}
return dt;
}
Now you just need to make a Partial (which LocalDate is) for the day of the week.
Partial().with(DateTimeFieldType.dayOfWeek(), DateTimeConstants.FRIDAY);
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 <.
Solution 5
import java.util.Calendar;
private Calendar getNextweekOfDay(int weekOfDay) {
Calendar today = Calendar.getInstance();
int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
int daysUntilNextWeekOfDay = weekOfDay - dayOfWeek;
if (daysUntilNextWeekOfDay == 0) daysUntilNextWeekOfDay = 7;
Calendar nextWeekOfDay = (Calendar)today.clone();
nextWeekOfDay.add(Calendar.DAY_OF_WEEK, daysUntilNextWeekOfDay);
return nextWeekOfDay;
}
// set alarm for next Friday 9am
public void setAlarm() {
Calendar calAlarm = getNextweekOfDay(Calendar.FRIDAY);
calAlarm.set(Calendar.HOUR_OF_DAY, 9);//9am
calAlarm.set(Calendar.MINUTE, 0);
calAlarm.set(Calendar.SECOND, 0);
scheduleAlarm(calAlarm);// this is my own method to schedule a pendingIntent
}
michael.kebe
Updated on July 05, 2022Comments
-
michael.kebe almost 2 years
How can I get the next friday with the Joda-Time API.
The
LocalDate
of today istoday
. 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.
-
michael.kebe over 14 yearsThanks for your answer. Your suggestion with the more general approach is nice. But the oneliner is awkward in term of readability.
-
fvu over 14 years@michaelkebe you asked for a oneliner, I just provided one... ;-)
-
David Victor almost 13 yearsor compile it ... "DateTimeConstans"
-
gyorgyabraham almost 11 yearsYour last snippet's "return" line contains a redundant ")" character. Anyways, thanks, great solution!
-
gyorgyabraham almost 11 years@michael.kebe I usually place newlines with ternaries at "?" and ":", hit format in Eclipse and it arranges pretty well.
-
Christopher Francisco about 8 yearsDoes this uses joda-time?
-
michael.kebe about 8 yearsNo, but it developed from it. Here a quote from the joda time homepage: Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).
-
Basil Bourque almost 8 yearsFYI, the java.time classes are built into Java 8 and later. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP. Also, see Oracle Tutorial to learn more.
-
Basil Bourque over 5 yearsFYI, the terribly troublesome old date-time classes such as
java.util.Date
,java.util.Calendar
, andjava.text.SimpleDateFormat
are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle. -
Basil Bourque over 5 yearsFYI, the terribly troublesome old date-time classes such as
java.util.Date
,java.util.Calendar
, andjava.text.SimpleDateFormat
are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle. -
Breton F. over 5 yearsYes If you use java 8 or onwards version or Jodatime, this is not for you. I did say it but i was not clear. Thanks for commenting.
-
Ole V.V. over 3 yearsHow is it better than the accepted answer? I guess it’s correct, but I have a very hard time convincing myself.
-
Nestor Milyaev over 3 yearsno-one saying it's better, just an alternative way of doing the same. I believe my answer has clear logic and it doesn't require knowledge/usage of different APIs/ classes other than LocalDate