問題

我有一種情況,我想將時間新增到日期,並在工作日周圍包裝新的日期.我修補了一個函式來確定這個新的日期,但是想確保我不會忘記任何東西.

要新增的時間稱為“延遲”。它可以很容易地成為函式的引數。

請釋出任何建議.[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