Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Batch File Time Comparison

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

like image 666
Brian Avatar asked Jan 11 '13 16:01

Brian


1 Answers

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.

like image 71
David Ruhmann Avatar answered Oct 13 '22 12:10

David Ruhmann