Parsing the current date from a command prompt

It's often handy to be able to rename a file so that its filename includes the current date. Fortunately, since at least Windows XP, cmd.exe's wonder for /f option provides a way to do this:

REM parse current date
for /f "tokens=2,3,4 delims=/ " %%i in ('echo %DATE%') DO (
set YEAR=%%i
set MONTH=%%j
set DAY=%%k

This can be used later on in the .bat file with:

move /Y somefile.txt somefile-%YEAR%-%MONTH%-%DAY%.txt

The above snippet assumes that it's embedded inside of a .bat file (replace double %s with single % if executed interactively). To prevent naming collisions I usually embed the snippet between SETLOCAL and ENDLOCAL commands.

No comments:

Post a Comment