How to get and display yesterday date?
I am using the date command for a batch script.
I am wondering how to use command date to get yesterday date.
Solution 1:
The main danger with the date variable is the locale sensitivity. If you have PowerShell available (it's a lot more common these days even in the big corporations) then you can use PowerShell to do the formatting and wrap it within a batch FOR statement.
The following PowerShell line will do the maths and format the date for you:-
PowerShell $date = Get-Date; $date=$date.AddDays(-1); $date.ToString('yyyy-MM-dd')
You can then execute this via FOR to get it into a batch file variable (remembering to escape a whole bunch of characters with the hat ^ symbol, and using the backtick to avoid the embeded quotes):-
for /f "usebackq" %%i in (`PowerShell $date ^= Get-Date^; $date ^= $date.AddDays^(-1^)^; $date.ToString^('yyyy-MM-dd'^)`) do set YESTERDAY=%%i echo %YESTERDAY%
I'm sure someone with superior PowerShell and Batch programming skills can reduce the PowerShell command and/or the number of escaped characters to make it more readable/maintainable.
Solution 2:
Anytime you hear batch, think Rob Van der Woude. Anyway, here's yesterday.bat.