How to get yesterday's date in a particular fo

2020-04-18 06:13发布

问题:

I need to set Today and yesterday's date in a variable in a fixed format YYYYMMDD.

For today date, when i did

SET TODAY=%date:~10,4%%date:~4,2%%date:~7,2%

it worked and displayed '20190426'. But how to set yesterday's date so I get it in the format - 20190425 ?

回答1:

Update The original unix and linux tags were later changed to cmd and batch-file, which this Linux / Bash / sh solution won't apply to.

To get yesterday's date:

$ date +%Y%m%d --date yesterday
20190425

To get it into a var:

$ var=$(date +%Y%m%d --date yesterday)
$ echo $var
20190425


回答2:

There are literally hundreds/thousands of questions just here on SO.

I suggest you use a PowerShell one-liner for this, which you can call from a batch file as follows:

@echo off
for /f "usebackq delims=" %%A in (`
  powershell -NoP -C "'{0:yyyyMMdd}' -f (Get-Date).AddDays(-1)"
`) do set YESTERDAY=%%A

%YESTERDAY% will then contain 20190824 when invoked on 25 August 2019, for instance.

A slightly longer variant, incorporating both today and yesterday in only one PowerShell invocation.

:: Q:\Test\2019\04\26\SO_55862158.cmd
@echo off
for /f "usebackq delims=" %%A in (`
    powershell -NoP -C "'yesterday={0:yyyyMMdd}' -f (Get-Date).AddDays(-1);'today={0:yyyyMMdd}' -f (Get-Date)"
`) do set "%%A"

The PowerShell part issues two lines

yesterday=20190824
today=20190825

which are parsed by the for /f and set as environment variables yesterday/today respectivly.



回答3:

You can use this batch/vbs hybrid, you need to save it as a .bat or .cmd extension file.:

@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 "final=%yyyy%%mm%%dd%"
echo %final%

Note, you can toggle the number of days in the set day=-1 line.



回答4:

Previously posted answers are not pure Batch-file solutions... You may use the method explained at this answer or just use this simpler approach:

@echo off
setlocal

set /A "YYYY=%date:~10,4%, MM=1%date:~4,2%, M=MM-100, DD=1%date:~7,2%, D=DD-100"
echo TODAY: %YYYY%%MM:~1%%DD:~1%

set /A "C1=!(D-=1),M-=C1*(1-12*(C2=!(M-1))),YYYY-=C1*C2,MM=100+M,DD=100+(D+=C1*(30+((M+(M>>3))&1)-!(M-2)*(2-!(YYYY%%4))))"
echo YESTERDAY: %YYYY%%MM:~1%%DD:~1%