Sounds simple enough, right? Turns out, it's not that easy in Java! Here's my solution:
public static Date getNextOccurenceOfDay(Date today, int dayOfWeek) {
Calendar cal = Calendar.getInstance();
cal.setTime(today);
int dow = cal.get(Calendar.DAY_OF_WEEK);
int numDays = 7 - ((dow - dayOfWeek) % 7 + 7) % 7;
cal.add(Calendar.DAY_OF_YEAR, numDays);
return cal.getTime();
}
Turns out that the % (mod) in Java doesn't deal with negative numbers that well, but by using the trick of doing a double-mod, you get the right answer!
You simply call this method with the starting date, and then tell it to target, for example, Calendar. SATURDAY, and it will give you the date of the next Saturday!
No comments:
Post a Comment