8

I am trying to compare current system time to a set time. Please 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 am and 10:45pm then perform this action otherwise perform the other.

The problem is this doesn't work. The results constantly vary. I think it has to do with my comparison to i.e., 07:00

1 Answer 1

12

The reason your script is failing is for time before 10 AM. When the time is less than 10, the %Time% variable returns this format: " H:MM:SS:ss". However when 10 or later the %Time% variable returns this format: "HH:MM:SS:ss".

Note the missing 0 at the beggining of the times before 10 is missing. This causes a comparison issue since batch is doing a string comparison and not a numeric comparison.

07:00 is less than 6:00 due to the fact that the ASCII value of 6 is greater than the ASCII value of 0.

The solution requires that you append a zero to the beginning of the time if it is before 10AM.

Just change

set currentTime=%TIME%

Into

set "currentTime=%Time: =0%"

This will replace any spaces in the time with zeros.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.