Jatin Gera
Jatin Gera

Reputation: 824

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.

Upvotes: 3

Views: 4603

Answers (3)

a guest
a guest

Reputation: 11

If you only care about hour boundaries then the built-in @HOUR macro is simplest/easiest:

If @HOUR >= 13 And @HOUR < 17 Then

...etc

Upvotes: 1

Octoplayer
Octoplayer

Reputation: 11

A simpler version that works for me - just using string compare in hh:mm format

#include <Date.au3>

Func _timeBetween( $sTime, $eTime)
    Return (_NowTime(4) < $eTime) And (_NowTime(4) > $eTime)
EndFunc  ; ==>_timeBetween


MsgBox(0, "daytime","is day = " & _timeBetween("08:00"."23:00") )

Upvotes: 1

Xenobiologist
Xenobiologist

Reputation: 2151

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

Upvotes: 4

Related Questions