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!