在Java 中,計算兩個日期之間的工作日數(不包括星期六和星期日)可以使用經過驗證的方法來實現.
Java 8 及更高版本:
對於Java 8 及更高版本,利用java.time 套件中的類可以簡化此任務:
<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>
Java 8 之前的版本:
對於Java 8 之前的版本,可以使用以下方法:
<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>
重要提示: 這些方法假設開始日期和結束日期是互斥的,這意味著它們不會包含在計數中。
以上是如何用Java計算兩個日期之間的工作天數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!