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!