How to get yesterday's date in a particular fo

2020-04-18 06:16发布

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 ?

4条回答
家丑人穷心不美
2楼-- · 2020-04-18 06:49

Update The original and tags were later changed to and , 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
查看更多
Anthone
3楼-- · 2020-04-18 06:51

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%
查看更多
Explosion°爆炸
4楼-- · 2020-04-18 06:53

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.

查看更多
狗以群分
5楼-- · 2020-04-18 06:56

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.

查看更多
登录 后发表回答