简体   繁体   中英

Previous Day Variable in a Batch File

I need to write a batch file that call a command and passes a date parameter for the previous day.

Example:

[function] CCYYMMDD

I can't seem to find any example of this. And my company doesn't like us to use freeware so I really need the solution to be a purely DOS based solution.

You could start with Dostips: Date and Time
There are functions to evaluate a date to a serial day count and vice versa.
So it's results to

call :jdate "%date%" JD_result
set /a prev_day=JD_result-1
call :jdate2date %prev_day% YYYY MM DD
echo Previous day is %DD%.%MM%.%YYYY%

I can't find the original solution I had for this but I found something over at Rob Van Der Woude's site that will do the job nicely.

There is a bug in the file posted there, due the the fact that SET /A will treat strings that start with a zero as octal, and this causes problems when day/month dates start with a zero.

If you get the files linked above, but change the code of the:JDate procedure (line 157) to:

SET MonthChecker1=%2
SET MonthChecker2=%MonthChecker1:~0,1%
IF %MonthChecker2%==0 (
  SET MonthChecker3=%MonthChecker1:~1,1%
) ELSE (
  SET MonthChecker3=%MonthChecker1%
)
SET DayChecker1=%3
SET DayChecker2=%DayChecker1:~0,1%
IF %DayChecker2%==0 (
  SET DayChecker3=%DayChecker1:~1,1%
) ELSE (
  SET DayChecker3=%DayChecker1%
)
SET /A Month1 = ( %MonthChecker3% - 14 ) / 12
SET /A Year1  = %1 + 4800
SET /A JDate  = 1461 * ( %Year1% + %Month1% ) / 4 + 367 * ( %MonthChecker3% - 2 -12 * %Month1% ) / 12 - ( 3 * ( ( %Year1% + %Month1% + 100 ) / 100 ) ) / 4 + %DayChecker1% - 32075
FOR %%A IN (Month1 Year1) DO SET %%A=
GOTO:EOF

This is tested and working on a 2K8R2 box. It is definitely worth using this over other solutions out there, as it has the capability to determine what the date format on the host system is from the registry, which no other solution I have found does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM