Page 1 of 1

Generating consecutive dates

Posted: 20 Mar 2019 10:29
by Aacini
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

Re: Generating consecutive dates

Posted: 21 Mar 2019 10:14
by aGerman
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

Re: Generating consecutive dates

Posted: 09 Apr 2022 09:10
by miskox
Test: 20200101 -2 returns 20191231. I guess it should be 20191230?

Code: Select all

C:\gendates.cmd
Enter base date in YYYYMMDD format: 20200101
Enter number of [+-]days: -2
2020/01/01
2019/12/31
C:\
1-jan-2020 - 1 day = 31-dec-2019
1-jan-2020 - 2 days = 30-dec-2019

?

The same goes if I enter +2.

Thanks.
Saso

Re: Generating consecutive dates

Posted: 13 Apr 2022 07:07
by jfl
Aacini's algorithm does not calculate the date N days away.
It displays N consecutive dates forwards (N positive), or backwards (N negative), starting at the given date.

If you want N consecutive dates 1 to N days away, simply reverse the echo and set instructions in the inner-most loop blocks.
And if you want a single date N days away, move the echo out of the loops, to the end of script.
But in the latter case, this code quickly becomes inefficient (O(N)) when N gets large.
In that case, the usual algorithm using an intermediate Julian Day Number is much more efficient (O(1)).