Scripting: Why Scripts Fail In August
Date calculations are not natively supported In batch scripting, so checking, for example, if a file has been updated recently can be achieved simply by comparing the relative number of months between the system time and the file time.
So if the current time is 3rd March 2019, and the file is 14th November 2018, this could be compared by calculating 2019*12+3 and 2018*12+11. The difference is 4 (24231-24227) so the file is older than three months. Very simple and good enough for some tasks.
However, with command processor (CMD) arithmetic, this can fail. The following will process as expected:
set /A _DATE=2019*12 + 03
The following will trip over:
set /A _DATE=2019*12 + 08
Invalid number. Numeric constants are either decimal (17),
hexadecimal (0x11), or octal (021).
The explanation is that command-line tools in Windows often return days and months as two digits, with a leading zero if less than 10. When processing arithmetic, CMD sees a number with a leading 0 as a hexadecimal number. Thus “07” is still 7 and processes as expected, whereas “08” is not a hexadecimal number.
The solution is to remove the leading zero, which can be done quickly by prepending the value with 100 and performing a modulo with the %% operator:
SET /A _NewM=100%_M%%%100