Tuesday, May 20, 2014

Appending the current date to the file-name in a DOS batch program

I was writing a utility batch for my backup folders and wanted to have the current date appended to the filename. Using just %DATE% was throwing errors as the default output of the date command contains a space on Windows. For e.g. echo %DATE% would return "Tue 05/20/2014".

The following format of the %DATE% command did the job for me. A good trick to have in your sleeve :)
echo %date:~-10,2%-%date:~-7,2%-%date:~-4,4%

This formatting essentially trims chars from the end and then truncates. Just copy-paste fragments of the above string to understand how this works. For e.g. echo %date:~-10%

I had used this to create a date-stamped jar file as follows.
jar -cvf backup_%date:~-10,2%-%date:~-7,2%-%date:~-4,4%.jar data/*