【发布时间】:2010-12-06 20:51:30
【问题描述】:
我想简单地使用内置的 dateadd 函数来计算一个新的日期,但要考虑到只应计算工作日(或者可以说是“工作日”)。
我想出了这个简单的算法,它不关心假期等。我已经用一些简单的日期对此进行了测试,但如果可以以更好的方式完成,我希望得到一些输入。
此示例假设一周有 5 个工作日(周一至周五),其中一周的第一天是周一。此处使用的日期格式为 d-m-yyyy,示例以 2009 年 10 月 1 日的开始日期计算。
这是简单的形式:
Dim d_StartDate As DateTime = "1-10-2009"
Dim i_NumberOfDays As Integer = 12
Dim i_CalculateNumberOfDays As Integer
If i_NumberOfDays > (5 - d_StartDate.DayOfWeek) Then
i_CalculateNumberOfDays = i_NumberOfDays
Else
i_CalculateNumberOfDays = i_NumberOfDays + (Int(((i_NumberOfDays + (7 - d_StartDate.DayOfWeek)) / 5)) * 2)
End If
MsgBox(DateAdd(DateInterval.Day, i_CalculateNumberOfDays, d_StartDate))
我尝试用以下代码来解释:
''' create variables to begin with
Dim d_StartDate as Date = "1-10-2009"
Dim i_NumberOfDays as Integer = 5
''' create var to store number of days to calculate with
Dim i_AddNumberOfDays as Integer
''' check if amount of businessdays to add exceeds the
''' amount of businessdays left in the week of the startdate
If i_NumberOfDays > (5 - d_StartDate.DayOfWeek) Then
''' start by substracting days in week with the current day,
''' to calculate the remainder of days left in the current week
i_AddNumberOfDays = 7 - d_StartDate.DayOfWeek
''' add the remainder of days in this week to the total
''' number of days we have to add to the date
i_AddNumberOfDays += i_NumberOfDays
''' divide by 5, because we need to know how many
''' business weeks we are dealing with
i_AddNumberOfDays = i_AddNumberOfDays / 5
''' multiply the integer of current business weeks by 2
''' those are the amount of days in the weekends we have
''' to add to the total
i_AddNumberOfDays = Int(i_AddNumberOfDays) * 2
''' add the number of days to the weekend days
i_AddNumberOfDays += i_NumberOfDays
Else
''' there are enough businessdays left in this week
''' to add the given amount of days
i_AddNumberOfDays = i_NumberOfDays
End If
''' this is the numberof dates to calculate with in DateAdd
dim d_CalculatedDate as Date
d_CalculatedDate = DateAdd(DateInterval.Day, i_AddNumberOfDays, d_StartDate)
提前感谢您的 cmets 和对此的投入。
【问题讨论】:
-
当正确的结果是 2009 年 1 月 27 日时,我认为您的算法在 10-jan-2009 (26-jan-2009) 没有给出正确的结果。
-
确实如此。我忘了提到我在这里使用 dd-mm-yyyy 格式。所以当我编译它说 1-oktober-2009。对不起,会改变问题。