Generating consecutive dates

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Aacini
Expert
Posts: 1597
Joined: 06 Dec 2011 22:15
Location: México City, México

Generating consecutive dates

#1 Post by Aacini » 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.

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))"
   )
)
Antonio

aGerman
Expert
Posts: 3623
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Generating consecutive dates

#2 Post by aGerman » 21 Mar 2019 10:14

Nice piece of code, Antonio! It fails with the century rule of leap years, but we will not write batch codes anymore when this becomes relevant :lol:

Steffen

Post Reply