Tuesday, April 24, 2012

Use Date and Time in batch file variables and filenames

http://www.intelliadmin.com/index.php/2007/02/create-a-date-and-time-stamp-in-your-batch-files/
http://kennethhunt.com/archives/000933.html
http://ss64.com/nt/syntax-gettime.html
http://sourceforge.net/projects/unxutils/files/
http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-us

 The FOR command is long known to be useful for parsing the "date /t" command, or output of any command. (Use "FOR /?" for details.) Without going into the development or practice, below is a batch file example for making the string "YYYYMMDD-HHMMSShh".

The Date/Time format varies between OS, so YMMV.  I just discovered the first link using the substring ability "~" in environment vars.  XP doesn't put the leading "0" on hours in %time%, so I used time /t here. Cut and paste the single long line and you should be fine. Note, the %time% variable changes as you might expect, so you need to set a var if you need consistency throughout the batch file.

Also note the last 2 links regarding a port of the Unix DATE.EXE might make this much simpler, though not built into the O/S.


rem echo %date% %time%
rem date /t
rem time /t
for /f "usebackq tokens=1,2,3* delims=/:. " %%a in (`time /t`) do set now=%date:~-4,4%%date:~4,2%%date:~7,2%-%%a%%b%time:~-5,2%%time:~-2,2%
echo %now%

There's also this version, that works on Windows 2012, relying solely on %date% and %time%:

set now=%date:~-4,4%%date:~4,2%%date:~7,2%-%time:~0,2%%time:~3,2%%time:~6,2%%time:~9,2%
echo %now%

No comments:

Post a Comment