更新:现在是2016年,我将使用PowerShell,除非有一个真正令人信服的向后兼容的原因,特别是因为使用日期的区域设置问题。参见@npocmaka的https://stackoverflow.com/a/19799236/8479


什么是Windows命令行语句(s),我可以使用以我可以放入文件名的格式获取当前日期时间?

我想要一个.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。我不想安装额外的实用程序来实现这一点(尽管我知道有一些工具可以很好地格式化日期)。


当前回答

另外两种不依赖于时间设置的方法(都来自:如何获得数据/时间独立于本地化:)。它们都可以获得星期几,而且都不需要管理权限!:

MAKECAB - will work on EVERY Windows system (fast, but creates a small temp file) (the foxidrive script): @echo off pushd "%temp%" makecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul >nul for /f "tokens=3-7" %%a in ('find /i "makecab"^<~.rpt') do ( set "current-date=%%e-%%b-%%c" set "current-time=%%d" set "weekday=%%a" ) del ~.* popd echo %weekday% %current-date% %current-time% pause More information about get-date function. ROBOCOPY - it's not native command for Windows XP and Windows Server 2003, but it can be downloaded from microsoft site. But is built-in in everything from Windows Vista and above: @echo off setlocal for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * \ \ /ns /nc /ndl /nfl /np /njh /XF * /XD *') do ( set "dow=%%D" set "month=%%E" set "day=%%F" set "HH=%%G" set "MM=%%H" set "SS=%%I" set "year=%%J" ) echo Day of the week: %dow% echo Day of the month : %day% echo Month : %month% echo hour : %HH% echo minutes : %MM% echo seconds : %SS% echo year : %year% endlocal And three more ways that uses other Windows script languages. They will give you more flexibility e.g. you can get week of the year, time in milliseconds and so on. JScript/batch hybrid (need to be saved as .bat). JScript is available on every system form NT and above, as a part of Windows Script Host (though can be disabled through the registry it's a rare case): @if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment @echo off cscript //E:JScript //nologo "%~f0" exit /b 0 *------------------------------------------------------------------------------*/ function GetCurrentDate() { // Today date time which will used to set as default date. var todayDate = new Date(); todayDate = todayDate.getFullYear() + "-" + ("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" + ("0" + todayDate.getDate()).slice(-2) + " " + ("0" + todayDate.getHours()).slice(-2) + ":" + ("0" + todayDate.getMinutes()).slice(-2); return todayDate; } WScript.Echo(GetCurrentDate()); VSCRIPT/BATCH hybrid (Is it possible to embed and execute VBScript within a batch file without using a temporary file?) same case as JScript, but hybridization is not so perfect: :sub echo(str) :end sub echo off '>nul 2>&1|| copy /Y %windir%\System32\doskey.exe %windir%\System32\'.exe >nul '& echo current date: '& cscript /nologo /E:vbscript "%~f0" '& exit /b '0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM. '1 = vbLongDate - Returns date: weekday, monthname, year '2 = vbShortDate - Returns date: mm/dd/yy '3 = vbLongTime - Returns time: hh:mm:ss PM/AM '4 = vbShortTime - Return time: hh:mm WScript.echo Replace(FormatDateTime(Date,1),", ","-") PowerShell - can be installed on every machine that has .NET - download from Microsoft (v1, v2, v3 (only for Windows 7 and above)). It is installed by default on everything from Windows 7/Windows Server 2008 and above: C:\> powershell get-date -format "{dd-MMM-yyyy HH:mm}" To use it from a batch file: for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do @set _date=%%# Self-compiled jscript.net/batch (never seen a Windows machine without .NET, so I think this is a pretty portable): @if (@X)==(@Y) @end /****** silent line that start JScript comment ****** @echo off :::::::::::::::::::::::::::::::::::: ::: Compile the script :::: :::::::::::::::::::::::::::::::::::: setlocal if exist "%~n0.exe" goto :skip_compilation set "frm=%SystemRoot%\Microsoft.NET\Framework\" :: Searching the latest installed .NET framework for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do ( if exist "%%v\jsc.exe" ( rem :: the javascript.net compiler set "jsc=%%~dpsnfxv\jsc.exe" goto :break_loop ) ) echo jsc.exe not found && exit /b 0 :break_loop call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0" :::::::::::::::::::::::::::::::::::: ::: End of compilation :::: :::::::::::::::::::::::::::::::::::: :skip_compilation "%~n0.exe" exit /b 0 ****** End of JScript comment ******/ import System; import System.IO; var dt=DateTime.Now; Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss")); Logman This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows XP and above. It probably will be never used by anybody - including me - but is one more way... @echo off setlocal del /q /f %temp%\timestampfile_* Logman.exe stop ts-CPU 1>nul 2>&1 Logman.exe delete ts-CPU 1>nul 2>&1 Logman.exe create counter ts-CPU -sc 2 -v mmddhhmm -max 250 -c "\Processor(_Total)\%% Processor Time" -o %temp%\timestampfile_ >nul Logman.exe start ts-CPU 1>nul 2>&1 Logman.exe stop ts-CPU >nul 2>&1 Logman.exe delete ts-CPU >nul 2>&1 for /f "tokens=2 delims=_." %%t in ('dir /b %temp%\timestampfile_*^&del /q/f %temp%\timestampfile_*') do set timestamp=%%t echo %timestamp% echo MM: %timestamp:~0,2% echo dd: %timestamp:~2,2% echo hh: %timestamp:~4,2% echo mm: %timestamp:~6,2% endlocal exit /b 0 One more way with WMIC which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer): for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in ("%%#") do @set %%@ echo %day% echo %DayOfWeek% echo %hour% echo %minute% echo %month% echo %quarter% echo %second% echo %weekinmonth% echo %year% Using TYPEPERF with some efforts to be fast and compatible with different language settings and as fast as possible: @echo off setlocal :: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance ::if defined USERDOMAIN_roamingprofile (set "v=v4") else (set "v=") for /f "tokens=4 delims=. " %%# in ('ver') do if %%# GTR 5 (set "v=v4") else ("v=") set "mon=" for /f "skip=2 delims=," %%# in ('typeperf "\UDP%v%\*" -si 0 -sc 1') do ( if not defined mon ( for /f "tokens=1-7 delims=.:/ " %%a in (%%#) do ( set mon=%%a set date=%%b set year=%%c set hour=%%d set minute=%%e set sec=%%f set ms=%%g ) ) ) echo %year%.%mon%.%date% echo %hour%:%minute%:%sec%.%ms% endlocal MSHTA allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October. <!-- : Batch portion @echo off setlocal for /f "delims=" %%I in ('mshta "%~f0"') do set "now.%%~I" rem Display all variables beginning with "now." set now. goto :EOF end batch / begin HTA --> <script> resizeTo(0,0) var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1), now = new Date(), props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes', 'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay', 'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth', 'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString', 'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'], output = []; for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())} close(fso.Write(output.join('\n'))); </script>

其他回答

我也遇到过类似的问题。我每天都会从FTP服务器上自动下载一个加密文件。我想使用gpg解密文件,将文件重命名为当前日期(YYYYMMDD格式),并将解密文件放入正确部门的文件夹中。

我根据日期查看了几个重命名文件的建议,直到我偶然发现了这个简单的解决方案。

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

它工作得很好(例如,文件名显示为“2011-06-14.txt”)。

(源)

下面是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<-------------

为了让代码在没有错误msg的情况下工作到stderr,我必须在变量赋值%%a, %%b和%%c周围添加单引号。我的locale (PT)在循环/解析的某个阶段导致了错误,比如执行“set =20”之类的东西。引号为赋值语句的左侧生成一个令牌(尽管为空)。

缺点是混乱的区域变量名称:'yy', 'mm'和'dd'。但是,谁在乎呢!

我使用date.exe,并将其重命名为date_unxutils.exe以避免冲突。 把它放在批处理脚本旁边的bin文件夹中。

Code

:: Add binaries to temp path
IF EXIST bin SET PATH=%PATH%;bin

:: Create UTC Timestamp string in a custom format
:: Example: 20210128172058
set timestamp_command='date_unxutils.exe -u +"%%Y%%m%%d%%H%%M%%S"'
FOR /F %%i IN (%timestamp_command%) DO set timestamp=%%i
echo %timestamp%

Download UnxUtils

链接。

参考文献

我建立在这个很棒的答案上。

一个基于wmic的函数:

:Now  -- Gets the current date and time into separate variables
::    %~1: [out] Year
::    %~2: [out] Month
::    %~3: [out] Day
::    %~4: [out] Hour
::    %~5: [out] Minute
::    %~6: [out] Second
  setlocal
  for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t
  endlocal & (
    if "%~1" neq "" set %~1=%T:~0,4%
    if "%~2" neq "" set %~2=%T:~4,2%
    if "%~3" neq "" set %~3=%T:~6,2%
    if "%~4" neq "" set %~4=%T:~8,2%
    if "%~5" neq "" set %~5=%T:~10,2%
    if "%~6" neq "" set %~6=%T:~12,2%
  )
goto:eof

优点:独立于地区。缺点:只有系统管理员才能运行wmic.exe。

用法:

call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%

它像这样回显一个字符串:

2014-01-22 12:51:53

注意,函数形参是外形参——也就是说,您必须提供变量名而不是值。

所有参数都是可选的,因此调用:Now Y M是一个有效的调用,如果您只想获得年和月。

简单回答:

 :: Start - Run , type:
 cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip"

 :: click into target media, Ctrl + V to paste the result 

长回答

    @echo off
    :: START USAGE  ==================================================================
    ::SET THE NICETIME 
    :: SET NICETIME=BOO
    :: CALL GetNiceTime.cmd 

    :: ECHO NICETIME IS %NICETIME%

    :: echo nice time is %NICETIME%
    :: END USAGE  ==================================================================

    echo set hhmmsss
    :: this is Regional settings dependant so tweak this according your current settings
    for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c 
    ::DEBUG ECHO hhmmsss IS %hhmmsss%
    ::DEBUG PAUSE
    echo %yyyymmdd%
        :: this is Regional settings dependant so tweak this according your current settings
    for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set  yyyymmdd=%%F%%E%%D
    ::DEBUG ECHO yyyymmdd IS %yyyymmdd%
    ::DEBUG PAUSE


    set NICETIME=%yyyymmdd%_%hhmmsss%
    ::DEBUG echo THE NICETIME IS %NICETIME%

    ::DEBUG PAUSE