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

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 04:21:30520browse

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

Determining Business Days Between Given Dates in Java

In Java, calculating the number of business days (excluding Saturdays and Sundays) between two dates can be achieved using proven methods.

Java 8 and Beyond:

For Java 8 and later versions, leveraging classes from the java.time package simplifies this task:

<code class="java">import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class BusinessDaysCalculator {

    public static int getWorkingDaysBetweenTwoDates(LocalDate startDate, LocalDate endDate) {
        return (int) ChronoUnit.DAYS.between(startDate, endDate) - getWeekends(startDate, endDate);
    }

    private static int getWeekends(LocalDate startDate, LocalDate endDate) {
        return (int) Math.floor(ChronoUnit.DAYS.between(startDate, endDate) / 7) * 2;
    }
}</code>

Pre-Java 8:

For versions prior to Java 8, the following approach can be utilized:

<code class="java">import java.util.Calendar;

public class BusinessDaysCalculator {

    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;

        if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
            return 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.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
                ++workDays;
            }
        } while (startCal.getTimeInMillis() < endCal.getTimeInMillis()); 

        return workDays;
    }
}</code>

Important Note: The methods assume that the start and end dates are exclusive, meaning they won't be included in the count.

The above is the detailed content of How to Calculate the Number of Business Days 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