How to get yesterday's date in a particular format? - datetime

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 ?

Update The original unix and linux tags were later changed to cmd and batch-file, 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

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.

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.

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%

Related

Output sortable date and time string with Windows batch file [duplicate]

This question already has answers here:
Batch command date and time in file name
(15 answers)
How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?
(30 answers)
Time is set incorrectly after midnight
(4 answers)
Closed 2 years ago.
I have gone through many similar questions such as the below, and cannot get a working output. I just need "YYYYMMDD-hhmmss" in a string. Below working is immediately ready to copy/paste into a command prompt and you can see the result. I do not know why there gaps/spaces between my variables in the final output (I thought there were trailing spaces, but I tried various techniques to strip those and none worked, there are no trailing spaces in the variables from what I can see). EDIT: I cannot use PowerShell (I would if I could, Gerhard correctly suggests that below but I am constrained by existing systems to batch).
Can someone advise how to create the expected string output of "YYYYMMDD-hhmmss" please?
Expected result: 20200716-100205
Actual result: 2020 07 16-10 02 05
Windows batch: formatted date into variable
:: for /f %x in ('wmic path win32_localtime get /format:list ^| findstr "="') do set %x
:: Inside a script use:
:: for /f %%x in ('wmic path win32_localtime get /format:list ^| findstr "="') do set %%x
set Year=2020
set Year=00%Year% && set Year=%Year:~-2% && echo %Year%
set Month=7
set Month=00%Month% && set Month=%Month:~-2% && echo %Month%
set Day=16
set Day=00%Day% && set Day=%Day:~-2% && echo %Day%
set Hour=10
set Hour=00%Day% && set Hour=%Hour:~-2% && echo %Hour%
set Minute=2
set Minute=00%Minute% && set Minute=%Minute:~-2% && echo %Minute%
set Second=5
set Second=00%Second% && set Second=%Second:~-2% && echo %Second%
set yyyymmddhhmmss=%Year%%Month%%Day%-%Hour%%Minute%%Second%
echo %yyyymmddhhmmss%
This answer has been extended numerous times, so I am removing everything and giving a single solution.
#
for /f "tokens=2 delims=.=" %%i in ('wmic os get localdatetime /format:list') do set result=%%i
echo %result%

Command for Job status history in Autosys

Can we get the status of an autosys job for the past 20 days. not the -r command which given that particular day. the whole 20 days.
I think -r can give you what you want. Try executing below:
autorep –j <your job name> -r -19
I give you AUTOHIST.cmd Slow as heck but works from command line.
#echo off
SET JOB_NAME=%~1
IF [%JOB_NAME%]==[] GOTO Usage
SET NUM_ENTRIES=%~2
IF [%NUM_ENTRIES%]==[] SET NUM_ENTRIES=10
SET /A NUM_ENTRIES=%NUM_ENTRIES%-1
SET HIST_START=%~3
IF [%HIST_START%]==[] SET HIST_START=0
SET SKIP_HEADER=0
FOR /L %%R IN (%HIST_START%, 1, %NUM_ENTRIES%) DO (
CALL :HistoricalAutoRep %%R
)
GOTO :EOF
:HistoricalAutoRep
IF [%SKIP_HEADER%]==[0] (
SET OPTIONS="delims="
) ELSE (
SET OPTIONS="skip=3 delims="
)
FOR /F %OPTIONS% %%F IN ('CALL AUTOREP -J %JOB_NAME% -r -%1') DO ECHO %%F
SET SKIP_HEADER=1
GOTO :EOF
:Usage
ECHO AUTOHIST ^<Required job name^> [Optional number of historic runs to return] [Optional number of runs back to start querying history]
GOTO :EOF

Compare directory name to string

I've created this very simple batch file for the sake of testing a concept I'm hoping to utilize. I need to recursively delete all of one type of file except in folders with a specific name. Here's my code:
:recur
FOR /f %%a IN ('DIR /b') DO (
IF EXIST %%a\NUL (
IF ["%%a" NEQ "subtest2"] (
ECHO %%a
CD %%a
CALL :recur
CD ..
)
)
COPY "*.cfm" "*_copy.cfm"
REM DEL "*_copy*.cfm"
)
Right now I'm just testing using copy instead of delete. Basically, this should create a copy of all the .cfm files except in the folder "subtest2". Right now it's recursively making the copies everywhere, including subtest2. How do I stop this?
The structure of my base directory is:
TestFolder
---subtest1
------test.pdf
------test.txt
------test.cfm
---subtest2
------test.pdf
------test.txt
------test.cfm
---test.pdf
---test.txt
---test.cfm
---recur.bat
The square brackets are not balanced on both sides of the IF comparison, so it can never match. The brackets are not part of the IF syntax. If present, they simply become part of the string that is compared. The same is true for any enclosing quotes. Remove the square brackets, and it will work (assuming there are no other problems)
Here is a simple method to accomplish your goal. I've prefixed the DEL command with ECHO for testing purposes:
for /r /d %%F in (*) do echo %%F\|findstr /liv "\\subtest2\\" >nul && echo del "%%F\*.cfm"
The FOR /R /D simply recurses all folders. The full path of each folder is piped into a FINDSTR command that looks for paths that do not contain a \subtest2 folder. The ECHO DEL command is only executed if the \subtest2\ folder is not found in the path.
Remove the last ECHO when you have confirmed the command gives the correct results.
Change %%F to %F if you want to run the command on the command line instead of in a batch file.
for f in `find . -path YOURDIR -prune -o print`
do
rm whateveryouwanttodelete
done
the find command in backticks finds all files but ignores the directory -prune you want to ignore. Then in the body of the loop you nuke the files. You can do even better with
find . -path YOURDIR -prune -o -print0 | xargs -0 rm -f
no need for the loop. DISCLAIMER: I haven't tested it so perhaps you want to start adopting it with cp instead of rm.
You can try this:
#echo off&setlocal
for /r /d %%i in (*) do (
pushd "%%i"
echo(%%i|findstr /ri "\\subtest2$" || COPY "*.cfm" "*_copy.cfm"
popd
)

Batch file: get file timestamp date only and age in days

The following few lines output the names of certain files in a folder, a delimiter, and a timestamp.
for /f "eol=: delims=" %%F in (
'dir /b /a-d /one *.txt *.pdf *.doc* *.xls* *.msg 2^>nul'
) do echo %indent%%fileBullet% %%F%delimeter% %%~tF
So, produces something like this
Response.docx; 02/07/2013 12:13 PM
I'd like to remove the time portion of the timestamp (so date only), followed by how many days old the file is. So
Response.docx; 02/07/2013; 14
I've found some fairly lengthy solutions online that contain a dozen or so lines. Is there a short and sweet approach?
Here's something shorter and sweeter. It's not as short and sweet as you'd like, but at least it's not 12 lines of code. :)
for /f "eol=: delims=" %%F in (
'dir /b /a-d /one *.txt *.pdf *.doc* *.xls* *.msg 2^>nul'
) do call :datediff "%indent%%fileBullet% %%F%delimeter%" %%~tF
goto :EOF
:datediff
echo wscript.echo DateDiff^("d", "%2", Date^(^)^)>"%temp%\dd.vbs"
set /P i="%~1 %2%delimeter% "<NUL
cscript /nologo "%temp%\dd.vbs"
del /q "%temp%\dd.vbs"

Batch For Loop w/ Timestamp

I need to rename multiple files in a loop and include a time stamp... My struggles begin with updating the timestamp for each file so the file has a unique name.
setlocal enabledelayedexpansion
SET date=%date:~-4,4%%date:~-10,2%%date:~-7,2%
for /f %%a in ('dir /b TCA_*') do (SET
time=%time:~-11,2%%time:~-8,2%%time:~-5,2%%time:~-2,2%
ren %%a %date%TCA_%time%.txt)
Thanks
While in a loop, variables don't update. To circumnavigate this, the setlocal enabledelayedexpansion script was added.
Basically, if you want them to update, you need to encase them in exclamation marks (!) instead of percent signs (%).

Resources