如何在Windows命令行上獲取當前的日期時間,以適合的格式在文件名中使用?



Answers

區域獨立的日期時間解析

%DATE%dir命令的輸出格式是區域相關的,因此既不健壯也不智能。 date.exeUnxUtils一部分)以任何可想像的格式提供任何日期和時間信息。 您也可以使用date.exe從任何文件中提取日期/時間信息。

示例:(在cmd腳本中使用%%而不是%)

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:任何文字

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

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

來自參考文件的日期/時間信息:
date.exe -rc:\file.txt +"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S"

在CMD腳本中使用它獲取年,月,日,時間信息:

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

在CMD腳本中使用它獲取任何所需格式的時間戳:

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

從任何參考文件中提取日期/時間信息。

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

向文件添加日期/時間信息:

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是不需要安裝date.exe

注意:將date.exe複製到搜索路徑中的任何目錄可能會導致其他腳本失敗,並使用Windows內置date命令。

Question

更新:現在是2016年,我會使用PowerShell進行此操作,除非有非常令人信服的向後兼容原因,特別是因為使用date的區域設置問題。 請參閱@ npocmaka的https://.com/a/19799236/8479

什麼是Windows命令行語句我可以使用什麼格式來獲取當前日期時間,我可以將它放入文件名?

我想要一個.bat文件,將當前日期和時間作為名稱的一部分壓縮到一個存檔中,例如Code_2008-10-14_2257.zip 。 有沒有簡單的方法可以做到這一點,獨立於機器的區域設置?

我真的不介意日期格式,理想情況下它會是yyyy-mm-dd,但任何簡單的事情都可以。

到目前為止,我已經得到了這個,在我的機器上給了我Tue_10_14_2008_230050_91

rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%

rem Now use the timestamp by in a new ZIP file name.
"d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code

我可以忍受這一點,但它似乎有點笨重。 理想情況下,它會更簡短,並具有前面提到的格式。

我正在使用Windows Server 2003和Windows XP Professional。 我不想安裝額外的實用程序來實現這一點(雖然我意識到有一些會做好日期格式)。




Regional independent solution generating the ISO date format:

rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCU\Control Panel\International" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format 
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:

What could still be optimized: Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated




這是我用過的:

::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%

如果您想要自動備份到7-Zip存檔的更多想法,我有一個您可以使用或查看想法的免費/開放項目: http://wittman.org/ziparcy/ : http://wittman.org/ziparcy/




I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.

:: Check your local date format
echo %date%

    :: Output is Mon 08/15/2016

:: get day (start index, number of characters)
::         (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
    :: output is Mon 

:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
    :: output is 08

:: get date 
set mydate=%DATE:~7,2% 
echo %mydate%
    :: output is 15

:: get year
set myyear=%DATE:~10,4%
echo %myyear%
    :: output is 2016



這並不簡單,但可能是一種更靈活的方式( 信用 ):

FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%



Given a known locality, for reference in functional form. The ECHOTIMESTAMP call shows how to get the timestamp into a variable ( DTS in this example.)

@ECHO off

CALL :ECHOTIMESTAMP
GOTO END

:TIMESTAMP
SETLOCAL  EnableDelayedExpansion
    SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!
    SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!
    SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!
ENDLOCAL & SET "%~1=%DTS%"
GOTO :EOF

:ECHOTIMESTAMP
SETLOCAL
    CALL :TIMESTAMP DTS
    ECHO %DTS%
ENDLOCAL
GOTO :EOF

:END

EXIT /b 0

And saved to file, timestamp.bat, here's the output:




以下是來自alt.msdos.batch.nt的一個獨立於本地的變體。

把它放在一個文本文件中,例如getDate.cmd

-----------8<------8<------------ snip -- snip ----------8<-------------
    :: Works on any NT/2k machine independent of regional date settings
    @ECHO off
    SETLOCAL ENABLEEXTENSIONS
    if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
    for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
      for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
        set '%%a'=%%i
        set '%%b'=%%j
        set '%%c'=%%k))
    if %'yy'% LSS 100 set 'yy'=20%'yy'%
    set Today=%'yy'%-%'mm'%-%'dd'% 
    ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%

    ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]

    :EOF
-----------8<------8<------------ snip -- snip ----------8<-------------

為了讓代碼能夠正常工作,無需將錯誤消息添加到stderr中,我必須為%% a,%% b和%% c添加單引號。 我的語言環境(PT)在循環/解析中的某個階段導致錯誤,例如“set = 20”的內容正在執行。 引號會為賦值語句的左側生成一個令牌(儘管為空)。

缺點是混亂的區域設置變量名稱:'yy','mm'和'dd'。 但是,嘿,誰在乎!




我有類似的問題。 I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.

I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.

for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt

It worked perfectly (ie, the filename comes out as "2011-06-14.txt").

(Source)




不幸的是,這對區域設置不是免疫的,但它可以做到你想要的。

set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%

驚人的東西,你可以找到Wikipedia




我使用的批處理文件更改了答案 ,因此它也適用於荷蘭語。
荷蘭人 - 像我們一樣持久 - 在%date%date/t和打破原始批處理文件的date有一些變化。

如果有些人可以對其他Windows語言環境進行檢查,並返回結果,那將會很好。
如果批處理文件在您的位置失敗,請在命令提示符處包含這兩條語句的輸出:
echo:^|date
date/t

這是您應該從批處理文件獲得的輸出示例:

C:\temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103

以下是修改後的代碼,並對原因進行了評論:

:: https://.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by jeroen@pluimers.com for Dutch locale
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
::            set '%%c'=%%k
::            set 'yy'=%%k
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
::        if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
@ECHO off
    set v_day=
    set v_month=
    set v_year=

    SETLOCAL ENABLEEXTENSIONS
    if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
::DEBUG echo toks=%toks%
      for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
        if "%%a" GEQ "A" (
          for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
            set '%%a'=%%i
            set '%%b'=%%j
            set 'yy'=%%k
          )
        )
      )
      if %'yy'% LSS 100 set 'yy'=20%'yy'%
      set Today=%'yy'%-%'mm'%-%'dd'%

    ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%

    ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
    set datestring=%V_Year%%V_Month%%V_Day%
    echo %datestring%

    :EOF

--jeroen




以下是一種在單行中獲取日期時間的方法:

for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %a in ('%date% %time%') do echo %c-%a-%b %d%e

在美國這將輸出“yyyy-mm-dd hhmm”。 不同的區域設置會導致不同的%date%輸出,但您可以修改令牌順序。

如果您需要其他格式,請通過重新排列令牌或使用不同(或不)分隔符來修改echo語句。




另一種方式( credit ):

@For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @( 
    Set Month=%%A
    Set Day=%%B
    Set Year=%%C
)

@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%

請注意,我的答案仍然依賴區域設置確定的日期和月份的順序 - 不確定如何解決該問題。




馬修約翰遜的單線解決方案獲得單線日期和時間是雄辯和有用的。

但是,它需要一個簡單的修改來從批處理文件中進行工作:

for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e





Related