Command Line Timestamp

I often write little batch scripts, sometimes just as a way to save a lengthy command line.  Frequently I also want to output the result to a file and give it a unique (and meaningful) filename.  However the built-in %date% and %time% variables expand to the unuseful "Fri 01/04/2008" and "15:35:51.14" which are difficult (or impossible) to use in a NTFS filename.  %random% is always an option, but a timestamp is always preferred.

I found an option in the SET command syntax which allowed me to create the following example.

 @echo off
echo year: %date:~-4%
echo mon : %date:~4,2%
echo day : %date:~7,2%
echo hour: %time:~0,2%
echo min : %time:~3,2%
echo sec : %time:~6,2%
echo.

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

Running this produces the following output.

 year: 2008
mon : 01
day : 04
hour: 16
min : 09
sec : 09

20080104_160909

It works on Windows Server 2003 and Windows Vista, however I don't know if non-default regional settings change the behavior of these variables.

Disclaimer: The information on this site is provided "AS IS" with no warranties, confers no rights, and is not supported by the authors or Microsoft Corporation. Use of included script samples are subject to the terms specified in the Terms of Use .