计算两个日期之间的工作日数的最快算法? [英] Fastest algorithm to calculate the number of business days between two dates?
问题描述
我之前曾多次偶然发现这个问题,周围有一些 SO 答案,但它们非常慢,例如
I have stumbled upon this problem couple of times before and there are some SO answers around but they are extremely slow e.g.
def businessDaysBetween(startDate: DateTime, endDate: DateTime): Seq[DateTime] = {
1 to daysBetween(startDate, endDate) map {
startDate.withFieldAdded(DurationFieldType.days(), _)
} diff holidays filter {
_.getDayOfWeek() match {
case DateTimeConstants.SUNDAY | DateTimeConstants.SATURDAY => false
case _ => true
}
}
}
def daysBetween(startDate: DateTime, endDate: DateTime) =
Days.daysBetween(startDate.toDateMidnight(), endDate.toDateMidnight()).getDays()
我的问题不仅是如何计算两个日期之间的工作日数,而且是最快的解决方案.请注意,我只需要知道工作日数,而不是实际日期.
My question is not only how to compute the number of business days between two dates but also the fastest possible solution. Note that I only need to know the number of business days and not the actual dates.
推荐答案
在我看来,这是一个可读性稍强的版本,具有相同的 O(C)
复杂度:
Here is a slightly more readable version in my opinion with the same O(C)
complexity:
def getPreviousWorkDay(d: DateTime): DateTime = {
d.withDayOfWeek(Math.min(d.getDayOfWeek, DateTimeConstants.FRIDAY)).withTimeAtStartOfDay()
}
def businessDaysBetween(startDate: DateTime, endDate: DateTime): Int = {
val workDayStart = getPreviousWorkDay(startDate)
val workDayEnd = getPreviousWorkDay(endDate)
val daysBetween = Days.daysBetween(workDayStart, workDayEnd).getDays
val weekendDaysBetween = daysBetween / 7 * 2
val additionalWeekend = if(workDayStart.getDayOfWeek > workDayEnd.getDayOfWeek) 2 else 0
daysBetween - weekendDaysBetween - additionalWeekend
}
我认为一周从星期一开始(Joda 的默认设置).
I consider that the week starts on Monday (the default for Joda).
我还认为星期六和下一个星期五之间有 5 个工作日,而星期一和下一个星期五之间只有 4 个工作日.
I also consider that between a Saturday and the following Friday there are 5 business days, whereas between a Monday and the following Friday there are only 4 business days.
这篇关于计算两个日期之间的工作日数的最快算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!