Reputation: 23
I am working on a little batch program, and I am having problems with coding the time scripting, which I mean by allowing people in the program in a certain time. The certain time is having it open at 12:00 P.M, and having it close on 11:00 P.M. This is my script so far:
@echo off
set current_time=%time:~0,5%
rem This piece of code below is to make it start
if %current_time% == "12:00" goto :START
rem this piece of code below is to make it stop
if %current_time% == "23:00" goto :STOP
rem and if you know batch you'll get these two
if %current_time% lss "12:00" if %current_time% gtr "23:00" goto :STOP
if %current_time% gtr "12:00" if %current_time% lss "23:00" goto :START
:START
echo The program has successfully ran.
echo Press anything to exit now.
pause >nul
exit
:STOP
echo Sorry, but this program is closed. Come back at 12:00 P.M.
pause >nul
exit
When I try the code, it just completely ignores the time configuration and goes straight to the start procedure. Does anybody know how to fix this? Also, PLEASE NOTE: I am using Windows 10.
Upvotes: 2
Views: 148
Reputation:
As I mentioned you can use Timeout for a delay, but there is also
Choice - a one key input which responds with an errorlevel
which allows you to abort while delaying.
As aacini elaborates in his comment, variables store only strings Set /A and If try to convert to an integer if possible.
One thing to always remember is that numbers with a leading zero are treated as coded in octal (0x as hex.) This is important when dealing with date/time parts month days hours mins secs.
Here is an example of a stacked if else construct
@echo off
:loop
Set Now=%time:~0,2%%time:~3,2%
If "%Now:~0,1%" equ "0" Set Now=%Now:~1%"
cls&Echo %Time:~0,8% Now=%Now%
if %Now% geq 1200 (
if %Now% leq 2300 (
goto :START
) Else (
goto :Stop
)
) Else (
Goto :Stop
)
Rem Could never reach here
:START
echo The program has successfully ran.
echo Press anything to exit now.
pause >nul
exit
:STOP
echo Sorry, but this program is closed. Come back at 12:00 P.M.
echo To abort, hit A
Choice /T 2 /C AN /M "Abort [A/N] " /D N >NUL
If %ErrorLevel% == 1 exit /B
Goto :loop
Upvotes: 1
Reputation: 80138
if %current_time% lss "12:00" if %current_time% gtr "23:00" goto :STOP
current_time
may be eg. 12:57
. 12:57
and "12:57"
are totally different strings. You need to quote the variable wherever you are comparing it against a quoted value,
if "%current_time%" lss "12:00" if "%current_time%" gtr "23:00" goto :STOP
BUT whereas this will correct the comparison, this code performs an "and" function, so you are asking "time <12:00" AND "time > 23:00" which is never going to be true. Your next statement may become true, but since this statement never becomes true, batch will simply skip to the next statement. It ignores labels - they are just position-markers.
Upvotes: 1