How to use previous date in batch script with yyyy

2019-07-27 13:15发布

问题:

This is for current date, How do we use yesterday date ....?

@echo off
set YYYYMMDD=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2% 
set a=%YYYYMMDD%
echo %a%

回答1:

Something like this should do.

@echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
set "result=%yyyy%-%mm%-%dd%"
echo %result%
pause

Obviously by increasing set day=-1 to other numbers will deduct more days.

Simply double click the batch or run from cmd.exe prompt.



回答2:

Try this shorter method (and the only pure-Batch solution in this topic):

@echo off
setlocal EnableDelayedExpansion

set /A "YYYY=%DATE:~10,4%, MM=1%DATE:~4,2%-100, DD=1%DATE:~7,2%-101, Feb=28+^!(YYYY%%4)"

set "DPM= 31 31 %Feb% 31 30 31 30 31 31 30 31 30"
if %DD% equ 0 set /A "MM+=M=-1,DD=0%DPM: =+^!(MM-(M+=1))*%,YYYY-=^!MM,MM+=12*^!MM"
set /A "MM+=100,DD+=100"

set "a=%YYYY%%MM:~1%%DD:~1%"
echo %a%

If you want to know what happens here, remove the @echo off line and run the program...

If you still have doubts about the method used, then you may do several tests over += and ! operators, and how the parentheses work.

Note that this solution does not work to subtract a number of days different than one. However, it is not difficult to insert the required adjustments to do that.



回答3:

  1. Here's a script called yesterday.bat:
 @if (@x)==(@y) @end /***** jscript comment ******
     @echo off

     cscript //E:JScript //nologo "%~f0"
     exit /b 0

 @if (@x)==(@y) @end ******  end comment *********/

var d = new Date();
d.setDate(d.getDate() - 1);

var mm=(d.getMonth())+1
if (mm<10){
  mm="0"+mm;
}
var dd=d.getDate();
if (dd<10) {
 dd="0"+dd;
}
WScript.Echo(d.getFullYear()+""+mm+""+dd);

you can use it like

for /f %%a in ('yesterday.bat') do set "ystd=%%a"
  1. Here's a one-liner with powershell which you most probably have installed:

    powershell "[DateTime]::Today.AddDays(-1).ToString("""yyyyMMdd""")"
    

    and you can assign this to variable:

    for /f %%a in ('powershell "[DateTime]::Today.AddDays(-1).ToString("""yyyyMMdd""")"') do set ystd=%%a