2

Possible Duplicate:
joda time - add weekdays to date

How can I use the Joda library to subtract a certain number of weekdays (i.e. excluding weekends) from a date?

If the input date is Jan 14, 2013 (Monday) and I subtract 1 day, I would like the result to be Jan 11, 2013 (Friday). How can I accomplish this?

Community
  • 1
  • 1

1 Answers1

3

There may not be a way to do this directly with the Joda libraries, but you can write your own Java functionality. In the following example, the subtractWeekdays(d, num) method rolls a date d back by a given num of weekdays. The output of this example is Fri Jan 11 00:00:00 CST 2013 as desired.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class SimpleTest  {
   // NOTE: the input num must be positive.
   public static Date subtractWeekdays(Date d, int num) {
      int count = 0;
      Calendar c = Calendar.getInstance();
      c.setTime(d);

      do {
         c.add(Calendar.DAY_OF_YEAR, -1);
         if(isWeekday(c.get(Calendar.DAY_OF_WEEK))) {
            ++count;
         }
      } while(count < num);

      return c.getTime();
   }

   public static boolean isWeekday(int dayOfWeek) {
      return ((dayOfWeek != Calendar.SATURDAY) && (dayOfWeek != Calendar.SUNDAY));
   }

   public static void main(String[] argv) {
      try {
         SimpleDateFormat dateFormat = new SimpleDateFormat("MMM d, y");
         Date d = dateFormat.parse("Jan 14, 2013");
         Date d2 = subtractWeekdays(d, 1);
         System.out.println(d2);
      } catch(Exception ex) {}
   }
}
808sound
  • 7,866
  • 1
  • 15
  • 13