Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get and display yesterday date?

Tags:

batch-file

I am using the date command for a batch script.
I am wondering how to use command date to get yesterday date.

like image 858
nokheat Avatar asked Jun 02 '10 00:06

nokheat


People also ask

How can I get yesterday's date in SQL?

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.

How can I get yesterday's date from a new date?

Use the setDate() method to get the previous day of a date, e.g. date. setDate(date. getDate() - 1) .


1 Answers

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.

like image 57
Chris Oldwood Avatar answered Sep 21 '22 15:09

Chris Oldwood