Q. Another way to calculate date plus or minus n days?

Jerold Schulman

December 26, 2006

1 Min Read
ITPro Today logo in a gray background | ITPro Today

I had scripted previous date calculations, some of which are:

8293 How can I return the date that is plus or minus n days from today?

9977 How can I calculate the difference between two short dates?

0721 General purpose date math routine.

I have now scripted PorMdays.bat to return a date in YYYY-MM-DD format that is the result of adding or subtractingn days from a short date, or from TODAY.

The syntax for using PorMdays.bat is:

[call] PorMdays NewYYYY-MM-DD DATEorTODAY +or-NN

Where:

NewYYYY-MM-DD is a call directed numeric environment variable that will contain the resulting YYYY-MM-DD.DATEorTODAY   is a valid short date, or the literal TODAY.+or-NN        is the number to add or subtract from DATEorTODAY, like 0, or +1, or -1, or +365.

NOTE: Because NewYYYY-MM-DD is a valid short date, it can be used in subsequent calculations, as in the following silly example:

call PorMdays Thisday today 0call PorMdays Yesday %Thisday% -1call PorMdays Tomday %Yesday% +2@echo Today is %Thisday%, Yesterday was %Yesday%, and Tomorrow is %Tomday%

PorMdays.bat contains:

@echo offif {%4} NEQ {} @echo Syntax: [call] PorMdays NewYYYY-MM-DD DATEorTODAY +or-NN (call PorMdays YMD today -1)&goto :EOFif {%3} EQU {} @echo Syntax: [call] PorMdays NewYYYY-MM-DD DATEorTODAY +or-NN (call PorMdays YMD today -1)&goto :EOFsetlocalif /i "%2" EQU "TODAY" ( set DT=now) else ( set DT="%2")set RND=%RANDOM%@echo.s=DateAdd("d",%3,%DT%) >"%temp%%~n0_%RND%.vbs"@echo.WScript.Echo year(s)^&right(100+month(s),2)^&right(100+day(s),2) >>"%temp%%~n0_%RND%.vbs"for /f %%a in ('cscript //nologo "%temp%%~n0_%RND%.vbs"') do set YYYYMMDD=%%adel /q "%temp%%~n0_%RND%.vbs"set YMD=%YYYYMMDD:~0,4%-%YYYYMMDD:~4,2%-%YYYYMMDD:~6,2%endlocal&set %1=%YMD%


Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like