Exclude weekends using Java Calendar

By: Slav Kurochkin

In my current project, I have to grab the latest date add some days(based on the request) and parse it back to the testing framework. The key problem is to exclude weekends while adding a days, so for example, if the date falling on Sunday or Saturday, I should skip it and continue adding days on Monday.

Here is an example:

The starting date is on Thursday, system need add 3 more work days to continue test execution.
When I add 3 days it is falling on Sunday, which is not going provide correct output.
The code bellow will skip Saturday and Sunday and will add work days incrementally (one by one):

public class DateCalculator {

	 public static void main(String a[]){
		 String requestedDate; // output
	        String finalDate; // output2
	        SimpleDateFormat setDateFormat;  // sdf

	        String month = "10";
	        String day = "13";
	        String year = "2016";
	        int addDays = 3; 
	        setDateFormat = new SimpleDateFormat("MM/dd/yyyy");
	        Calendar c = Calendar.getInstance();
	        c.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
	        int workDays = 0;
	        do {
	            c.add(Calendar.DAY_OF_MONTH, 1);
	            if (c.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY
	            && c.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)
	            /* && !holidays.contains((Integer) startCal.get(Calendar.DAY_OF_YEAR))) */
	  } while (workDays < addDays);

	        finalDate = setDateFormat.format(c.getTime());
	        System.out.println("Here is new solution: " + finalDate);
View Comments

Leave a Comment

Use markdown or basic HTML and be nice.