How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

前端 未结 28 2162
别跟我提以往
别跟我提以往 2020-11-21 05:28

Update: Now that it\'s 2016 I\'d use PowerShell for this unless there\'s a really compelling backwards-compatible reason for it, particularly because of the regional setting

28条回答
  •  情深已故
    2020-11-21 05:47

    Regionally independent date time parsing

    The output format of %DATE% and of the dir command is regionally dependent and thus neither robust nor smart. date.exe (part of UnxUtils) delivers any date and time information in any thinkable format. You may also extract the date/time information from any file with date.exe.

    Examples: (in a cmd-script use %% instead of %)

    date.exe +"%Y-%m-%d"
    2009-12-22

    date.exe +"%T"
    18:55:03

    date.exe +"%Y%m%d %H%M%S: Any text"
    20091222 185503: Any text

    date.exe +"Text: %y/%m/%d-any text-%H.%M"
    Text: 09/12/22-any text-18.55

    Command: date.exe +"%m-%d """%H %M %S """"
    07-22 "18:55:03"`

    The date/time information from a reference file:
    date.exe -r c:\file.txt +"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S"

    Using it in a CMD script to get year, month, day, time information:

    for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n
    

    Using it in a CMD script to get a timestamp in any required format:

    for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe +"%%y-%%m-%%d %%H:%%M:%%S"') do set timestamp=%%i
    

    Extracting the date/time information from any reference file.

    for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n
    

    Adding to a file its date/time information:

    for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y-%%m-%%d.%%H%%M%%S"') do ren file.txt file.%%i.txt
    

    date.exe is part of the free GNU tools which need no installation.

    NOTE: Copying date.exe into any directory which is in the search path may cause other scripts to fail that use the Windows built-in date command.

提交回复
热议问题