Search code examples
autoit

How to write an AutoIt script that calculate when it ran first time in a day?


What would be an AutoIt script that should take the current time?


Solution

  • A function based way; formats result nicely and easy to understand:

    #include <Date.au3>
    
    Global $ini = "ini.ini"
    
    If _AlreadyRunToday() Then
        MsgBox(0, "Title", _Format(_Diff()))
    Else
        __SetTime()
    EndIf
    __SetDate()
    
    Func _AlreadyRunToday() ;Checks if the program run today yet
        If IniRead($ini, "Section", "D", "") <> @MDAY _
                Or IniRead($ini, "Section", "M", "") <> @MON _
                Or IniRead($ini, "Section", "Y", "") <> @YEAR Then Return False
        Return True
    EndFunc
    
    Func _ReadDate() ;Returns the time when the program run the first time in YYYY/MM/DD HH:MM:SS
        Return IniRead($ini, "Section", "Y", "") & "/" & IniRead($ini, "Section", "M", "") & "/" & IniRead($ini, "Section", "D", "") & " " & IniRead($ini, "Section", "H", "") & ":" & IniRead($ini, "Section", "Mi", "") & ":" & IniRead($ini, "Section", "S", "")
    EndFunc
    
    Func __SetDate() ;Sets the date the program run the last time
        IniWrite($ini, "Section", "D", @MDAY)
        IniWrite($ini, "Section", "M", @MON)
        IniWrite($ini, "Section", "Y", @YEAR)
    EndFunc
    
    Func __SetTime() ;Sets the time of the first instance running that day
        IniWrite($ini, "Section", "H", @HOUR)
        IniWrite($ini, "Section", "Mi", @MIN)
        IniWrite($ini, "Section", "S", @SEC)
    EndFunc
    
    Func _Diff() ;Calculates the seconds passed since the first run today
        Return _DateDiff("s", _ReadDate(), _NowCalc())
    EndFunc
    
    Func _Format($Seconds) ;Turns seconds to HH:MM:SS
        Local $h, $m, $s
        _TicksToTime($Seconds * 1000, $h, $m, $s)
        ;Return $h & ":" & $m & ":" & $s
        Return StringFormat("%02d:%02d:%02d", $h, $m, $s) ;As suggested by Samoth
    EndFunc