共用方式為


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 .

Comments

  • Anonymous
    January 01, 2003
    Rar76 - can you provide more detail where %date:~3,2% is more accurate?  %date:~4,2% returns the month value on every system I have, whereas %date:~3,2% returns a space and the first digit of the month. Now this is much powerful and easier in PowerShell: get-date -format MM. go.microsoft.com/fwlink has the available formatting option.

  • Anonymous
    October 28, 2011
    echo mon : %date:~4,2% is incorrect. echo mon : %date:~3,2% is correct.

  • Anonymous
    March 08, 2012
    Thanks!

  • Anonymous
    November 14, 2012
    The comment has been removed