Search code examples
javadatedayofweek

Java - Count Number of days except Holidays(Saturday and Sunday)


I need to count for number of days except holidays(Saturday and sunday). For example my start date is 07/02/2018 and end date is 15/02/2018 (in dd/MM/yyyy format). I need to count number of working days between them. Can some please help me out? This is my code:

SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");

//Date date12 = dateformat3.parse("17/07/1989");
String date1 = "11/07/2018";
String date2 = "20/07/2018";

// Date date2 = dateformat3.parse("15/10/2007");
Calendar startdate = Calendar.getInstance();
startdate.setTime(dateformat3.parse(date1));
Calendar enddate = Calendar.getInstance();
enddate.setTime(dateformat3.parse(date2));
while (!startdate.after(enddate)) {
    int day = startdate.get(Calendar.DAY_OF_WEEK);
    if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
        workingDays++;
    }
}

I've tried with this code but is not showing any result.


Solution

  • You were close, just need to increment start date inside while loop.

    public static void main(String[] args) throws Exception {
        System.out.println(countDays("07/02/2018", "15/02/2018"));
    }
    
    public static int countDays(String startDate, String endDate) throws Exception {
        int workingDays = 0;
    
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    
        Calendar startdate = Calendar.getInstance();
        startdate.setTime(sdf.parse(startDate));
        Calendar enddate = Calendar.getInstance();
        enddate.setTime(sdf.parse(endDate));
    
        while (!startdate.after(enddate)) {
            int day = startdate.get(Calendar.DAY_OF_WEEK);
            System.out.println(day);
            if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
                workingDays++;
            }
    
            // increment start date, otherwise while will give infinite loop
            startdate.add(Calendar.DATE, 1);
        }
    
        return workingDays;
    }
    

    As you can see, the only difference with the code I provided from yours (besides removing hard-coded values) is startdate.add(Calendar.DATE, 1);