Home  >  Article  >  Java  >  How to Calculate the Number of Weekdays Between Two Dates in Java?

How to Calculate the Number of Weekdays Between Two Dates in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 17:36:42413browse

How to Calculate the Number of Weekdays Between Two Dates in Java?

Calculate the Number of Weekdays Between Two Dates in Java

For those seeking a Java code snippet to calculate the number of business days (excluding weekends) between two dates, a popular response from 2011 proposed a solution utilizing the Calendar class. Despite Java 8's subsequent introduction of modern date-time handling capabilities through the java.time package, the following code demonstrates how to achieve this calculation using the Calendar API:

<code class="java">public static int getWorkingDaysBetweenTwoDates(Date startDate, Date endDate) {
    Calendar startCal = Calendar.getInstance();
    startCal.setTime(startDate);        
    
    Calendar endCal = Calendar.getInstance();
    endCal.setTime(endDate);

    int workDays = 0;

    //Return 0 if start and end are the same
    if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
        return 0;
    }
    
    if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {
        startCal.setTime(endDate);
        endCal.setTime(startDate);
    }

    do {
       //excluding start date
        startCal.add(Calendar.DAY_OF_MONTH, 1);
        if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
            ++workDays;
        }
    } while (startCal.getTimeInMillis() < endCal.getTimeInMillis()); //excluding end date

    return workDays;
}</code>

Note that this solution follows a "continuous" counting approach, excluding both the start and end dates themselves. For instance, if start and end are on a Monday and Friday, respectively, the method will return 4.

The above is the detailed content of How to Calculate the Number of Weekdays Between Two Dates in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn