Reputation: 44605
I have created a batch file that regularly gets triggered from an automated job.
Within the batch file, I want to check if time is between 12AM and 8AM, set a variable with a particular value, otherwise, set it to the default.
Any tips I how might do this in a batch file?
Upvotes: 3
Views: 10071
Reputation: 10500
I see this has already been answered, but the solution seems unnecessarily complicated to me. Also, some additional explanation might come in handy to understand the solution.
You can access the current time in a batch file by using %TIME%
:
C:\>echo %TIME%
18:01:52,64
You can use the following syntax to access a substring of %TIME%
(or any other variable, for that matter):
C:\>echo %TIME:~0,2%
18
Therefore, to conditionally set the variable as you described, you would do:
IF %TIME:~0,2% LSS 08 ( SET VAR=particularValue ) ELSE ( SET VAR=defaultValue )
Edit: Corrected solution with help from @dbenham - see his answer and comment to see what was wrong with my original attempt.
Upvotes: 5
Reputation: 130819
for /f "delims=:." %%T in ("%time%") do if %%T lss 08 (set var=someValue) else (set var=default)
Edit - zb226 is correct - the above is more complicated than need be. Much simpler to do
if %time:~0,2% lss 08 (set var=someValue) else (set var=default)
The leading 0 in 08 is critical. The reason is that numbers preceded by 0 are treated as octal notation, and 8 and 9 are not valid octal digits. The IF statement will do a string comparison if it sees an invalid octal number on either side. So if the current hour is 09, then 09 lss 8
is TRUE because 0 sorts before 8. Changing to 09 lss 08
gives the correct answer.
Either solution above sets the value to default if it is exactly 8:00:00.00 AM. If you really want the "particular value" through 8:00:00.00 AM and default any time after, then it is a bit more complex. In that case I would revert back to the FOR solution.
for /f "tokens=1-4 delims=:." %%A in ("%time%") do (
set var=default
if %%A lss 08 set var=someValue
if %%A%%B%%C%%D equ 08000000 set var=someValue
)
Upvotes: 5