Search code examples
timeautoit

How can I check if time lies between given times?


I am trying to check if time is between 13:00 and 17:00. I don't think _DateDiff() (using _DateAdd() and _NowTimeCalc()) will work. Is there some function or do I have to compare against @HOUR and @MIN?

I am doing this:

Func CheckTime($sStart, $sEnd)
    $s = StringSplit($sStart, ":")
    $e = StringSplit($sEnd, ":")
    $s[1] = Int($s[1])
    $s[2] = Int($s[2])
    $e[1] = Int($e[1])
    $e[2] = Int($e[2])
    $result = False

    If $s[0] <= 0 And $e <= 0 Then
        ConsoleWrite("Wrong Time Format")
        Exit
    EndIf

    If $s[1] <= @HOUR And $e[1] >= @HOUR Then
        If @HOUR >= $s[1] And @MIN > $s[2] Then
            If @HOUR <= $e[1] And @MIN < $e[2] Then
                $result = True
            EndIf
        EndIf
    EndIf
    Return $result
EndFunc  ; ==>CheckTime

This works when start time < end time, but I am looking for a method instead of manual checks.


Solution

  • Using standard user defined functions (UDFs), you can try using something like this:

    #region    ;************ Includes ************
    #include <Array.au3>
    #include <Date.au3>
    #endregion    ;************ Includes ************
    
    
    ConsoleWrite(_timeBetween(@HOUR & ':' & @MIN, '10:05', '12:09'))
    
    Func _timeBetween($cTime, $sTime, $eTime)
        If Not _DateIsValid('2000/01/01 ' & $cTime) Then Return -1
        If Not _DateIsValid('2000/01/01 ' & $sTime) Then Return -2
        If Not _DateIsValid('2000/01/01 ' & $eTime) Then Return -3
    
        ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') & @CRLF)
        ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') & @CRLF)
    
        If _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') < 0 And _
           _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') > 0 Then
    
            Return 1
        Else
            Return 0
        EndIf
    
    EndFunc  ; ==>_timeBetween