Generating consecutive dates
Posted: 20 Mar 2019 10:29
In some Batch-file applications the generation of consecutive dates is needed. The usual way to solve this problem is converting the base date to a Julian Day Number, increment/decrement this number by one and then convert it back to date. Other suggested method is using other languages that natively support date operations, like PowerShell or VBScript/JScript.
However, this problem may be solved in a very simple way via a pure Batch file that uses a single SET /A command with a somewhat large arithmetic expression.
Antonio
However, this problem may be solved in a very simple way via a pure Batch file that uses a single SET /A command with a somewhat large arithmetic expression.
Code: Select all
@echo off
setlocal EnableDelayedExpansion
set /P "YYYYMMDD=Enter base date in YYYYMMDD format: "
set /P "days=Enter number of [+-]days: "
set /A "DD=100+(D=YYYYMMDD%%100), YYYYMM=YYYYMMDD/100, MM=100+(M=YYYYMM%%100), YYYY=YYYYMM/100
if %days% lss 0 (
for /L %%i in (%days%,1,-1) do (
echo !YYYY!/!MM:~1!/!DD:~1!
set /A "C1=^!(D-=1),MM=100+(M-=C1*(1-12*(C2=^!(M-1)))),YYYY-=C1*C2,DD=100+(D+=C1*(30+((M+(M>>3))&1)-^!(M-2)*(2-^!(YYYY%%4))))"
)
) else (
for /L %%i in (1,1,%days%) do (
echo !YYYY!/!MM:~1!/!DD:~1!
set /A "C1=^!((D+=1)-(31+((M+(M>>3))&1)-^!(M-2)*(2-^!(YYYY%%4)))),MM=100+(M+=C1*(1-12*(C2=^!(M-12)))),YYYY+=C1*C2,DD=100+(D-=C1*(D-1))"
)
)