Search code examples
java

get number of working days in specific month


I want to get the number of working days in a specific month

in my case the weekend days are FRIDAY and SATURDAY

I use this code :

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

public class TestWeekDay {

    /**
     * @param args
     * @throws ParseException 
     */
    public static void main(String[] args) throws ParseException {

        // TODO Auto-generated method stub


        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        String dateInString = "01-07-2016";
        Date startDate = sdf.parse(dateInString);
        String dateInString2 = "31-07-2016";
        Date endDate = sdf.parse(dateInString2);
        calculateDuration(startDate,endDate);

    }



    public static int calculateDuration(Date startDate, Date endDate)
    {
      Calendar startCal = Calendar.getInstance();
      startCal.setTime(startDate);

      Calendar endCal = Calendar.getInstance();
      endCal.setTime(endDate);

      int workDays = 0;

      if (startCal.getTimeInMillis() > endCal.getTimeInMillis())
      {
        startCal.setTime(endDate);
        endCal.setTime(startDate);
      }

      do
      {
        startCal.add(Calendar.DAY_OF_MONTH, 1);
        if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY)
        {
          workDays++;
        }
      }
      while (startCal.getTimeInMillis() <= endCal.getTimeInMillis());

      return workDays;
    }

}

when I test for example for July month I have 22 and the correct response should be 21


Solution

  • Using the new Java dates

    public static int calculateDuration(LocalDate startDate, LocalDate endDate) {
        int workDays = 0;
        while(!startDate.isAfter(endDate)) {
          if (startDate.getDayOfWeek() != DayOfWeek.FRIDAY
                  && startDate.getDayOfWeek() != DayOfWeek.SATURDAY) {
            workDays++;
          }
          startDate = startDate.plusDays(1);
        }
        return workDays;
      }
    

    and then use it like below:

    var dur = calculateDuration(LocalDate.of(2024,9,1), LocalDate.of(2024,9,30));