I am using the date command for a batch script.
I am wondering how to use command date to get yesterday date.
To get yesterday's date, you need to subtract one day from today's date. Use CURDATE() to get today's date. In MySQL, you can subtract any date interval using the DATE_SUB() function. Here, since you need to subtract one day, you use DATE_SUB(CURDATE(), INTERVAL 1 DAY) to get yesterday's date.
Use the setDate() method to get the previous day of a date, e.g. date. setDate(date. getDate() - 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With