问题

我有一种情况,我想将时间添加到日期,并在工作日周围包装新的日期.我修补了一个函数来确定这个新的日期,但是想确保我不会忘记任何东西.

要添加的时间称为“延迟”。它可以很容易地成为函数的参数。

请发布任何建议.[VB.NET警告]

 Private Function GetDateRequired() As Date
    ''// A decimal representation of the current hour
    Dim hours As Decimal = Decimal.Parse(Date.Now.Hour) + (Decimal.Parse(Date.Now.Minute) / 60.0) 

    Dim delay As Decimal = 3.0           ''// delay in hours
    Dim endOfDay As Decimal = 12.0 + 5.0 ''// end of day, in hours
    Dim startOfDay As Decimal = 8.0      ''// start of day, in hours

    Dim newHour As Integer
    Dim newMinute As Integer

    Dim dateRequired As Date = Now
    Dim delta As Decimal = hours + delay

    ''// Wrap around to the next day, if necessary
    If delta > endOfDay Then
        delta = delta - endOfDay
        dateRequired = dateRequired.AddDays(1)

        newHour = Integer.Parse(Decimal.Truncate(delta))
        newMinute = Integer.Parse(Decimal.Truncate((delta - newHour) * 60))
        newHour = startOfDay + newHour
    Else
        newHour = Integer.Parse(Decimal.Truncate(delta))
        newMinute = Integer.Parse(Decimal.Truncate((delta - newHour) * 60))
    End If

    dateRequired = New Date(dateRequired.Year, dateRequired.Month, dateRequired.Day, newHour, newMinute, 0)

    Return dateRequired
End Sub
 

注意:如果延迟时间超过9小时,这可能不起作用.它不应该从3到3.

编辑: 目标是找到将几个小时添加到当前时间后的日期和时间.这用于确定提交日期的预期日期的默认值.我想在当前时间添加3个小时以获得到期日时间.但是,我不希望当天下午5点以外的到期日.所以,我试图在(今天,至下午5点)和(明天,从上午8点开始)之间分隔时间,这样将3个小时添加到下午4点将给你19点,因为今天结束时添加1个小时,明天开始时添加2个小时.

  最佳答案

好的,这些怎么样?这些方法之间的区别应该代表自己。

此外,这是我可以抛出它的测试.保修持续到现在...

希望它有帮助!

 Module Module1

    Public Function IsInBusinessHours(ByVal d As Date) As Boolean
        Return Not (d.Hour < 8 OrElse d.Hour > 17 OrElse d.DayOfWeek = DayOfWeek.Saturday OrElse d.DayOfWeek = DayOfWeek.Sunday)
    End Function


    Public Function AddInBusinessHours(ByVal fromDate As Date, ByVal hours As Integer) As Date
        Dim work As Date = fromDate.AddHours(hours)
        While Not IsInBusinessHours(work)
            work = work.AddHours(1)
        End While
        Return work
    End Function


    Public Function LoopInBusinessHours(ByVal fromDate As Date, ByVal hours As Integer) As Date
        Dim work As Date = fromDate
        While hours > 0
            While hours > 0 AndAlso IsInBusinessHours(work)
                work = work.AddHours(1)
                hours -= 1
            End While
            While Not IsInBusinessHours(work)
                work = work.AddHours(1)
            End While
        End While
        Return work
    End Function

    Sub Main()
        Dim test As Date = New Date(2008, 8, 8, 15, 0, 0)
        Dim hours As Integer = 5
        Console.WriteLine("Date: " + test.ToString() + ", " + hours.ToString())
        Console.WriteLine("Just skipping: " + AddInBusinessHours(test, hours))
        Console.WriteLine("Looping: " + LoopInBusinessHours(test, hours))
        Console.ReadLine()
    End Sub

End Module
 

  相同标签的其他问题

vb.netdate