通过减去工作日的开始日期时间和结束日期时间来获取期间

时间:2014-12-19 15:21:06

标签: vb.net datetime period

我正在尝试在VB.NET中实现一个可以减去开始日期时间和日期时间的方法,并产生这个特定的字符串句点“D.HH:mm:ss”,观察当天没有24小时,但只有8个小时。

我的减法函数只返回小时差异和小数:

Public Function WH(ByVal date1 As Date, ByVal date2 As Date, 
              Optional ByVal considerwk As Boolean = True) As Decimal

    Dim ini_tim As DateTime = DateTime.Parse("08:00")
    Dim end_tim As DateTime = DateTime.Parse("18:00")

    '//RESULT
    Dim _res As Integer

    '//WHILE INITIAL LESS THAN END...
    Do While date1 <= date2

        '//INSIDE INTERVAL?
        If Hour(date1) >= Hour(ini_tim) And Hour(date1) <= Hour(end_tim) Then

            '//CONSIDER WORKDAY?
            If considerwk = True Then
                '//IF NOT SATURDAY OR SUNDAY
                If Weekday(date1) <> vbSaturday And Weekday(date1) <> vbSunday Then

                    '//ADD +1 IN RESULT
                    _res += 1
                End If
            Else
                '//ADD +1 IN RESULT
                _res += 1
            End If
        End If

        '//ADD A MINUTE IN THE DATE
        date1 = DateAdd("n", 1, date1)
    Loop

    '//RETURN THE DIFF IN DEC
    Return CDec(_res / 60)

End Function

希望你能帮助我! 谢谢!

1 个答案:

答案 0 :(得分:1)

要考虑的事情......

使用您当前的代码:

Hour(date1) <= Hour(end_tim)

18:01的时间被认为是“在间隔内”,实际上是在结束时间之后!

尝试更像下面的内容。如果你的开始/停止时间不完全在一小时的最高点(如08:30到18:30),那么它可以精确到秒,并可以处理它:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim dt1 As DateTime = DateTime.Now
    Dim dt2 As DateTime = dt1.AddDays(5).AddHours(4).AddMinutes(39).AddSeconds(17)
    Dim ts As TimeSpan = WH(dt1, dt2, True)
    Dim strFormattedTotal As String = String.Format("{0}.{1}:{2}:{3}", ts.Days, ts.Hours.ToString("00"), ts.Minutes.ToString("00"), ts.Seconds.ToString("00"))
    Label1.Text = "Total: " & strFormattedTotal
    Label2.Text = "Total Hours: " & ts.TotalHours
End Sub

Public Function WH(ByVal date1 As Date, ByVal date2 As Date, Optional ByVal considerwk As Boolean = True) As TimeSpan
    Static ini_tim As DateTime = DateTime.Parse("08:00")
    Static end_tim As DateTime = DateTime.Parse("18:00")

    Dim TS As New TimeSpan
    Do While date1 < date2
        If date1.TimeOfDay >= ini_tim.TimeOfDay AndAlso date1.TimeOfDay <= end_tim.TimeOfDay Then
            If considerwk Then
                If date1.DayOfWeek <> DayOfWeek.Saturday AndAlso date1.DayOfWeek <> DayOfWeek.Sunday Then
                    TS = TS.Add(TimeSpan.FromSeconds(1))
                End If
            Else
                TS = TS.Add(TimeSpan.FromSeconds(1))
            End If
        End If
        date1 = date1.AddSeconds(1)
    Loop
    Return TS
End Function