Reputation: 253
I'm trying to understand a batch script I found online , the code is designed to check for the last day of the month and terminate the script if the condition is true.
Heres a copy of the code.
REM @echo off
for /F "tokens=1,2,3 delims=/ " %%a in ('echo %date%') do set day=%%a & set month=%%b & set year=%%c
set /a leap=%year% %% 3
if %leap%==0 (set eom=29) else (set eom=28)
echo 01 03 05 07 08 10 12 | find "%month%" > nul && set eom=31
echo 04 06 09 11 | find "%month%" > nul && set eom=30
rem if %eom%==%day% exit
however I understand the rest of the code all except the following two lines.
set /a leap=%year% %% 3
if %leap%==0 (set eom=29) else (set eom=28)
when I've tried to Echo the contents of the leap variable I keep getting 2, but if I'm honest don't truly understand how it would ever get 0 ?
any advice on this would be helpful.
Upvotes: 0
Views: 73
Reputation: 1071
%%
means modulus, since each leap year is 4 years apart e.g. 2012(leap),2013,2014,2015,2016(2nd leap), if value of a leap year is 0, then value of the last year before another leap year is 4.( Think of an array, [0,1,2,3,5], 0 to 4 is 5 numbers apart). And so, 2016 is another leap year, since its value 4 is the 5th number from 0.
If you still confused why modulo 4? Because the leap year divided by 4 is 0, so as I said before, 0 means a leap year.
Upvotes: 1
Reputation: 1832
It looks like The %leap%
variable is being used to check if a year is a leap year. You only ever get 2 when you echo %leap%
because 2015 % 3
will always be 2.
It also seems that the logic for checking if it's a leap year is flawed. A general approach for this is
- If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
- If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
- If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
- The year is a leap year (it has 366 days).
- The year is not a leap year (it has 365 days).
Upvotes: 0