tags:

views:

515

answers:

4

i am using the date command for a dos script. i am wondering how to use dos command "date" to get yesterday date.

A: 

Anytime you hear batch, think Rob Van der Woude. Anyway, here's yesterday.bat.

JRL
A: 

Looking at @JRL's answer... If it's truly that hard, perhaps use PowerShell and then do similar to http://stackoverflow.com/questions/2433941/powershells-get-date-how-to-get-yesterday-at-2200-in-a-variable

You can call to PowerShell in a bat file like so: http://stackoverflow.com/questions/1804751/use-bat-to-start-powershell-script

You'll end up with a three or four liner solution rather than the 100 or so written (immaculately I'll add) by Rob Van der Woude.

Good luck...

Reddog
0 i am reading this, which can help me format a string http://technet.microsoft.com/en-us/library/ee692801.aspxbut if i am going to get yesterday date and format the string, how to use this properly? (get-date).AddDays(-1) and Get-Date -format yyyyMMddso i get yesterday date in yyyyMMdd format?
nokheat
sorry i found it $a = (get-date).AddDays(-1);date $a -format yyyyMMddthanks, very good soltuibm reddog!!
nokheat
+1  A: 

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 echo %i

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.

Chris Oldwood
A: 

There is a much cheaper way of doing this, exclusively in batch. I know its rough, but it worked for me :)

Basically write yesterdays date into a text file (yesterday.txt) then call it next time the process runs. Works for a process I have that runs once a day only.

::pick up yesterdays date from file ::Needs to be done as the file generated today is yesterdays report. for /F "tokens=1" %%a IN (D:\BIN\Yesterday.txt) DO set yest=%%a

::Write todays date to file for use tomorrow echo %date% >D:\BIN\Yesterday.txt

Then you can call yesterdays date as Variable %yest%.

Patrick