Friday, September 28, 2012

How to determine the next occurrence of a day of the week in Java

I recently ran into a question around how to determine the next occurrence of a particular day of the week in Java. For example, if today is Tuesday, how do I figure out when the next Saturday is? Or, if it's Saturday, when is the next Wednesday?

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