Reputation: 3835
I run this script in windows batch
set currentTime=%TIME%
if %currentTime% lss 09:00 echo "Before 09:00"
and I get
60 was unexpected at this time.
If I remove the second % my script runs but it incorrectly returns "Before 09:00" no matter what time I compare. (I think it compares 09:00 with the literal %currentTime).
Can anyone help on how to properly compare time?
Upvotes: 1
Views: 5553
Reputation: 2565
For use pure bat to do this, you need use EnableDelayedExpansion
and use substring in time set, and work with if time layout are or not using AM/PM by change if from leq
to gtr
in %_bit_compare%
to parse the procedure, or...
It is some like another thing, that my limited English don't help me to explain to you very well, sorry..:
@echo off & setlocal EnableDelayedExpansion
set "currentTime=!TIME::=!" & set "currentTime=!currentTime:,=!" & set "conpareTime=900"
(set "_bit_compare=leq" & time /t | findstr /l "AM PM" || set "_bit_compare=gtr" )>nul
if "!currentTime:~0,4=!" %_bit_compare% "!conpareTime!" (echo/ !time:~0,5! Before 09:00) else (echo/ !time:~0,5! After 09:00)
Or, same code in non-compacted form:
@echo off & setlocal EnableDelayedExpansion
set "currentTime=!TIME::=!"
set "currentTime=!currentTime:,=!"
set "_bit_compare=leq"
set "conpareTime=900"
(time /t | findstr /l "AM PM" || set "_bit_compare=gtr")>nul
if "!currentTime:~0,4=!" %_bit_compare% "!conpareTime!" (
echo/ !time:~0,5! Before 09:00
) else (
echo/ !time:~0,5! After 09:00
)
Upvotes: 1
Reputation: 5504
You may also do this as follows:
@echo off
setlocal EnableDelayedExpansion
rem Set time to compare to 09:00:00:
set "time_to_compare=090000"
:loop
for /F "skip=1 delims=." %%A IN ('wmic OS get localdatetime') do (
for /F "delims=" %%B IN ("%%A") do (
set "_time=%%B"
if !_time:~-6! GEQ 090000 (call :after) else (call :before)
)
)
:after
echo It is after 09:00:00^^!
pause>nul
exit /b 0
:before
echo It is before 09:00:00^^!
pause>nul
exit /b 0
I don't know what you want to do. So, if it after, it will call
— not goto
— :after
subroutine and if before, it will call
:before
.
You can make any other changes you want.
Note: The time will be generated with the 24-hour and HH:mm:ss
format; if you meant 21:00:00
change set "time_to_compare=090000"
to set "time_to_compare=210000"
. The way this happened is to prevent misbehaviours. The solution is written in pure batch as requested.
Upvotes: 1
Reputation: 16236
Here is an easy way to do it in a cmd.exe
shell .bat file script.
FOR /F "delims=" %%a IN ('powershell -NoL -NoP -Command "(Get-Date).Hour"') DO (SET /A "HOUR=%%a")
IF %HOUR% LSS 9 (
ECHO "Before 09:00"
)
Upvotes: 4