Windows batch file time comparison

I am trying to compare the current system time with a given time. See below:

set currentTime=%TIME% set flag=false if %currentTime% geq 07:00 if %currentTime% leq 22:45 set flag=true if %flag%==true ( ) else ( ) 

If the time is between 7:00 and 22:45, then perform this action, otherwise do another.

The problem is that this does not work. Results are constantly changing. I think this is due to my comparison, that is, from 07:00

+7
source share
1 answer

The reason your script is not working is the time until 10 a.m. When the time is less than 10, the% Time% variable returns this format: " H:MM:SS:ss" . However, when 10 or later returns the variable %Time% : "HH:MM:SS:ss" .

Note the missing 0 at the start of the time before 10 . This causes a comparison problem because the package performs string comparisons rather than numerical comparisons.

07:00 less than 6:00 because ASCII 6 greater than ASCII 0 .

The solution requires you to add zero to the beginning of the time if it is before 10 in the morning.

Just change

 set currentTime=%TIME% 

IN

 set "currentTime=%Time: =0%" 

This will replace any spaces beyond zero.

+9
source

All Articles