Discussion forum for all Windows batch related topics.
Moderator: DosItHelp
-
Aacini
- Expert
- Posts: 1914
- Joined: 06 Dec 2011 22:15
- Location: México City, México
-
Contact:
#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: 4678
- Joined: 22 Jan 2010 18:01
- Location: Germany
#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
Steffen
-
miskox
- Posts: 630
- Joined: 28 Jun 2010 03:46
#3
Post
by miskox » 09 Apr 2022 09:10
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
-
jfl
- Posts: 226
- Joined: 26 Oct 2012 06:40
- Location: Saint Hilaire du Touvet, France
-
Contact:
#4
Post
by jfl » 13 Apr 2022 07:07
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)).