Shashi Kiran
Shashi Kiran

Reputation: 362

How to calculate the working days (excluding weekends) in between two different dates?

My requirement is to calculate the number of days between the given two dates, excluding Saturday and Sunday.

Example:

Start date: 10/09/15 and End date 18/09/15
Result: 7

Date is in DD/MM/YY format.

Code:

import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;

public class DaysCounter {
    private String startDate;
    private String endDate;

    public void calculateDate(){
        @SuppressWarnings("resource")
        Scanner in=new Scanner(new InputStreamReader(System.in));

        System.out.println("Enter the starting date (DD/MM/YY) :");
        startDate=in.next();

        System.out.println("Enter the End date (DD/MM/YY) :");
        endDate=in.next();

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try
        {
            Calendar start = Calendar.getInstance();
            start.setTime(sdf.parse(startDate));
            Calendar end = Calendar.getInstance();
            end.setTime(sdf.parse(endDate));
            int workingDays = 0;
            while(!start.after(end))
            {
                int day = start.get(Calendar.DAY_OF_WEEK);
                if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY))
                    workingDays++;
                start.add(Calendar.DATE, 1);
            }
            System.out.println(workingDays);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        DaysCounter daysCounter=new DaysCounter();
        daysCounter.calculateDate();
    }
}

Here are the results for the above code.

  1. Enter the starting date (DD/MM/YY) :
    14/09/15
    Enter the End date (DD/MM/YY) :
    20/09/15
    
    5
    
  2. Enter the starting date (DD/MM/YY) :
    14/09/15
    Enter the End date (DD/MM/YY) :
    17/09/15
    
    2
    
  3. Enter the starting date (DD/MM/YY) :
    31/08/15
    Enter the End date (DD/MM/YY) :
    30/09/15
    
    21
    

As seen in the above first example, the result is correct. However, for the second example, the result is incorrect, the expected result is 4. Also for the third example, the result is incorrect.

When I enter the date between any weekday and a Saturday, I get an incorrect result.

What changes should be made to the code to make it work?

Upvotes: 7

Views: 11595

Answers (3)

Nitesh Virani
Nitesh Virani

Reputation: 1712

You have a mistake in creating SimpleDateFormat, change to yy instead of yyyy

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");

This should solve your problems. I do not see any issues in your logic.

As per your comments, if your start date is greater than end date then you have to swap it before while loop

   if(start.after(end)) {
       Calendar tempCal;
       tempCal = start;
       start = end;
       end = tempCal;
    }

Upvotes: 5

/*this program is for count the days between two days with excluding SATURDAY and SUNDAY*/

package example;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

public class ValidDate {

    private static Pattern datePattern = Pattern.compile("^\\d{1,2}/\\d{1,2}/\\d{4}$");

    public static boolean isValidFormat(String src, String src1) {
        if (datePattern.matcher(src).matches() && datePattern.matcher(src1).matches()) {
            return true;
        }
        return false;
    }

    public static boolean isValidDate(String str, String str1) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);

        try {
            sdf.parse(str);
            sdf.parse(str1);
            return true;
        } catch (ParseException e) {
            return false;
        }

    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter start Date");
        String startDate = sc.next();

        System.out.println("Enter end date");
        String endDate = sc.next();

        int workingDays = 0;
        boolean isValidPattern = isValidFormat(startDate, endDate);
        if (isValidPattern) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            sdf.setLenient(false);
            if (isValidDate(startDate, endDate)) {
//System.out.println("This is valid dates");
                try {
                    Calendar start = Calendar.getInstance();
                    start.setTime(sdf.parse(startDate));
                    Calendar end = Calendar.getInstance();
                    end.setTime(sdf.parse(endDate));

                    while (!start.after(end)) {
                        int day = start.get(Calendar.DAY_OF_WEEK);
                        if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
                            workingDays++;
                        }
                        start.add(Calendar.DATE, 1);
                    }
                    System.out.println("Working Days=" + workingDays);
            
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                System.out.println("Given date is invalid");
            }
        } else {
            System.out.println("Please enter date in [DD/MM/YYYY] format");
        }
    }
}

Upvotes: 0

Animesh Kumar Paul
Animesh Kumar Paul

Reputation: 2294

Check the below code:

import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;


public class DaysCounter {
private String startDate;
private String endDate;

public void calculateDate(){
    @SuppressWarnings("resource")
    Scanner in=new Scanner(new InputStreamReader(System.in));

    System.out.println("Enter the starting date (DD/MM/YY) :");
    startDate=in.next();

    System.out.println("Enter the End date (DD/MM/YY) :");
    endDate=in.next();

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    try
    {
        Calendar start = Calendar.getInstance();
        start.setTime(sdf.parse(startDate));
        Calendar end = Calendar.getInstance();
        end.setTime(sdf.parse(endDate));
        int workingDays = 0;
        while(!start.after(end))
        {
            int day = start.get(Calendar.DAY_OF_WEEK);

            day = day + 2;
            if (day > 7){
                day = day -7;
            }

            if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY))
                workingDays++;
            start.add(Calendar.DATE, 1);
        }
        System.out.println(workingDays);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

public static void main(String[] args)
{
    DaysCounter daysCounter=new DaysCounter();
    daysCounter.calculateDate();
}
}

Upvotes: 3

Related Questions