7

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Shashi Kiran
  • 362
  • 2
  • 9
  • 27
  • http://stackoverflow.com/questions/15622413/calculate-business-days-in-java-without-saturdays-sunday-and-public-holiday OR http://stackoverflow.com/questions/4600034/calculate-number-of-weekdays-between-two-dates-in-java ... – XpiritO Sep 24 '15 at 10:08
  • @BenWin Yes I want the date difference, but including the start and the end date. – Shashi Kiran Sep 24 '15 at 10:16
  • @ShashiKiran I executed your program and it works fine. Gives 4 for the second example. – Dakshinamurthy Karra Sep 24 '15 at 10:25
  • @KDM Found the mistake in my code, the date format had to changed from yyyy to yy. Can you kindly recheck with the same data ? – Shashi Kiran Sep 24 '15 at 10:28
  • @ShashiKiran according to sdf java doc "For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D." – Dakshinamurthy Karra Sep 24 '15 at 10:29
  • @ShashiKiran while trying your code, I changed the format to "yy" and forgot about it. – Dakshinamurthy Karra Sep 24 '15 at 10:32
  • Do official holidays matter in your calculation ? – Marged Sep 24 '15 at 10:40
  • @Marged I need only the weekends to be removed not any other official or public holidays. – Shashi Kiran Sep 24 '15 at 10:42

3 Answers3

5

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;
    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Nitesh Virani
  • 1,688
  • 4
  • 25
  • 41
3

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();
}
}
Animesh Kumar Paul
  • 2,241
  • 4
  • 26
  • 37
  • This works fine. But if I enter the Start date greater than the End date getting the result as 0. Is there any logic for this? – Shashi Kiran Sep 24 '15 at 10:40
0
/*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");
        }
    }
}
  • in above programs you can enter date greater than 28/31 which is not applicable but in this code that problem is gone with the use of setLenient. – Dhruv Shantilal Patel Mar 21 '23 at 10:06
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 27 '23 at 13:31