0

My program needs two command line arguments to run: start_date and end_date.

I want my .bat file to generate these values automatically so that start_date will always hold the value of M days ago and end_date will hold the value of N days ago. They should also both be in the yyyyMMdd format.

E.g. if M=10, N=5 and today is 25th of September 2015, my program should run with the following parameters:

MyProgram.exe "start_date:20150915" "end_date:20150920"

How can I achieve this using only batch file commands?

disasterkid
  • 6,948
  • 25
  • 94
  • 179
  • 1
    Pure batch is horrible at date math. I'd use a JScript hybrid. You could also use PowerShell, but JScript or VBScript would be faster. – rojo Sep 24 '15 at 13:44
  • @rojo I am good at neither. Can you help me out? – disasterkid Sep 24 '15 at 13:46
  • 1
    Please note that SO is not a free code writing service; so try it yourself and ask a specific question when stuck... – aschipfl Sep 24 '15 at 13:48
  • @Pedram how are you at JavaScript? JScript uses the same syntax and a lot of similar methods. [This answer](http://stackoverflow.com/a/27297874/1683264) is a pretty decent example showing date math. Depending on your needs, you might also use `forfiles` to get files last modified more than *N* days ago, then use `forfiles` again to exclude files modified more than *M* days ago. – rojo Sep 24 '15 at 13:51
  • [this should help](http://stackoverflow.com/search?q=%5Bbatch-file%5D+get+yesterdays+date) – Stephan Sep 24 '15 at 13:52

1 Answers1

1
@echo off
setlocal EnableDelayedExpansion

set /A M=10, N=5

rem Separate current date in DD, MM and YYYY parts:
rem Modify next line accordingly to your locale date format (this one use "MM/DD/YYYY")
for /F "tokens=1-3 delims=/" %%a in ("%date%") do set /A mm=1%%a-100, dd=1%%b-100, yyyy=%%c

rem Convert today's date to Julian Day Number
call :DateToJulian %dd% %mm% %yyyy% today=

rem Subtract the given numbers of days
set /A start_date=today-M, end_date=today-N

rem Convert the new Julian Day Numbers back to dates
call :JulianToDate %start_date% start_date=
call :JulianToDate %end_date% end_date=

echo MyProgram.exe "start_date:%start_date%" "end_date:%end_date%"
goto :EOF


rem Convert a Date to Julian Day Number
:DateToJulian Day Month Year Julian=
set /A a=(%2-14)/12, %4=(1461*(%3+4800+a))/4+(367*(%2-2-12*a))/12-(3*((%3+4900+a)/100))/4+%1-32075
exit /B

rem Convert a Julian Day Number to Date in YYYYMMDD format
:JulianToDate Julian YYYYMMDD=
set /A l=%1+68569,n=(4*l)/146097,l=l-(146097*n+3)/4,i=(4000*(l+1))/1461001,l=l-(1461*i)/4+31,j=(80*l)/2447
set /A dd=100+l-(2447*j)/80,l=j/11,mm=100+j+2-(12*l),yyyy=100*(n-49)+i+l
set "%2=%yyyy%%mm:~1%%dd:~1%
exit /B

Reference: http://www.hermetic.ch/cal_stud/jdn.htm#comp
Aacini
  • 65,180
  • 12
  • 72
  • 108