.netvb.netbooleantimeofday

Check if timeofday is in a specified range


    Dim time As String = TimeOfDay.ToString("tt")
    Dim time2 As Integer = TimeOfDay.ToString("hh:mm:ss")
    If time = ("du.") Then
        timehre = (time2 + 12)
        Debug.WriteLine("munkaidoben")
    Else
        Debug.Write("munkaidoben = false")
        timehre = time
    End If

    For munkaido As Integer = 13 To 19

        If time2.ToString.Contains(munkaido) Then
            duplaar = False
        Else
            duplaar = True
        End If
    Next

Timehre is already declared as integrer.So,what i want,to get time in utc +1,and if time is in range of 13:00 - 19:00 then return a true boolean value,and if it is not in range of 13:00 - 19:00 then returning a false boolean value.

P.s. sorry for bad english,i hope you will understang my question.


Solution

  • First, turn on Option Strict:

    Dim time2 As Integer = TimeOfDay.ToString("hh:mm:ss")
    ...
    For munkaido As Integer = 13 To 19
        If time2.ToString.Contains(munkaido) Then
    

    This is a good example of why not using Option Strict is a very bad idea for other than toy programs. If the time is "10:45:23", the result in time2 will be 49! Where did that come from? It is the ASCII value of the first character in the string.

    Later, the code will test if the text "49" contains 13 - 19 which can never be true. With the conversion that happens, time2 can only ever be between"48" and "57". Syntactically, it is invalid because a string can never contain an integer.

    Not using Option Strict can result in this type of unwanted conversion and bugs. Don't leave the compiler to guess what you mean:
    Tools -> Options -> Projects and Solutions -> VB Defaults -> Option Strict On


    Your code is not really testing if the time is in a range, just whether 13-19 appear somewhere in the string. If the minutes or seconds are one of those values, it will validate.

    Dont use strings to do DateTime operations. The DateTime type has a full set of properties you can use:

    Dim dt = DateTime.Now
    
    If dt.Hour >= 13 AndAlso (dt.Hour <= 18 OrElse
                             (dt.Hour = 19 AndAlso dt.Minute = 0)) Then
        Return True
    Else
        Return False
    End If
    

    The code tests if the time is between 13:00 AND 19:00 rather than just the hour, in order to detect 19:01 or 19:59 which are the 19th hr but the minutes put it after 19:00, the hours and minutes are checked.

    I am not sure how UTC comes into play, but that is also easy using DateTime methods:

    Dim dt = DateTime.Now.ToUniversalTime()
    

    To add an hour:

    Dim dt = DateTime.Now.ToUniversalTime.AddHours(1)