How do I get current datetime on the Windows command line, in a suitable format for using in a filename?
更新:现在是2016年了,我会使用PowerShell来解决这个问题,除非有一个令人信服的向后兼容原因,特别是由于使用
我可以使用什么Windows命令行语句来获取当前日期时间,其格式可以输入文件名?
我想要一个.bat文件,它将一个目录压缩到一个归档文件中,并将当前日期和时间作为名称的一部分,例如,
我并不介意日期格式,理想情况下是YYYY-MM-DD,但是任何简单的事情都可以。
到目前为止,我已经得到了这个,在我的机器上,它给了我一个(2)EDOCX1:
1 2 3 4 5 6 7 8 9 | 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。我不想安装额外的实用程序来实现这一点(尽管我知道有一些实用程序可以很好地格式化日期)。
请参阅Windows批处理文件(.bat)以获取mmddyyyy格式的当前日期:
1 2 3 4 | @echo off For /f"tokens=2-4 delims=/" %%a in ('date /t') do (set mydate=%%c-%%a-%%b) For /f"tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b) echo %mydate%_%mytime% |
如果您喜欢24小时/军用格式的时间,可以将第二行替换为:
1 | For /f"tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b) |
C:> .\date.bat
2008-10-14_0642
如果希望日期独立于地区日/月顺序,则可以使用"wmic os get localdatetime"作为源,因为它是按ISO顺序排列的:
1 2 3 4 | @echo off for /F"usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6% echo Local date is [%ldt%] |
C:>test.cmd
Local date is [2012-06-19 10:23:47.048]
区域独立的日期时间分析
参考文件中的日期/时间信息:
在命令脚本中使用它来获取年、月、日、时间信息:
1 | 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 |
在命令脚本中使用它以任何所需格式获取时间戳:
1 | for /f"tokens=*" %%i in ('C:\Tools\etc\date.exe +"%%y-%%m-%%d %%H:%%M:%%S"') do set timestamp=%%i |
从任何引用文件中提取日期/时间信息。
1 | 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 |
将其日期/时间信息添加到文件中:
1 | 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是免费GNU工具的一部分,不需要安装。
注意:将
还有两种不依赖时间设置的方法(均取自:如何获取独立于本地化的数据/时间:)。而且两者都可以获得一周中的某一天,而且都不需要管理员权限!:
makecab-将在每个Windows系统上工作(快速,但创建一个小的临时文件)(foxidrive脚本):
1 2 3 4 5 6 7 8 9 10 11 12 | @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 |
有关获取日期函数的详细信息。
robocopy-它不是Windows XP和Windows Server 2003的本机命令,但可以从Microsoft网站下载。但内置于Windows Vista及更高版本的所有功能中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | @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 |
还有三种使用其他Windows脚本语言的方法。它们会给你更多的灵活性,例如你可以得到一年中的一周,以毫秒为单位的时间等等。
jscript/批混合(需要保存为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | @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混合(是否可以在不使用临时文件的情况下在批处理文件中嵌入和执行vbscript?)与JScript的情况相同,但杂交并不那么完美:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | :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-可以安装在每台具有.NET的计算机上-从Microsoft下载(v1、v2、v3(仅适用于Windows 7及更高版本))。默认情况下,它安装在Windows 7/Windows Server 2008及更高版本的所有设备上:
1 | C:\> powershell get-date -format"{dd-MMM-yyyy HH:mm}" |
要从批处理文件中使用它,请执行以下操作:
1 | for /f"delims=" %%# in ('powershell get-date -format"{dd-MMM-yyyy HH:mm}"') do @set _date=%%# |
自编译的jscript.net/batch(从未见过没有.net的Windows计算机,因此我认为这是一个相当可移植的工具):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | @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在其日志文件中放置的时间戳。它适用于Windows XP及更高版本的所有应用程序。它可能不会被任何人使用-包括我-但还有一种方法…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | @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 |
使用wmic还有一种方法,它还提供一年中的一周和一周中的一天,但不提供毫秒(毫秒请检查foxidrive的答案):
1 2 3 4 5 6 7 8 9 10 | 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% |
尽可能快地使用typeperf,使其快速兼容不同的语言设置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | @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允许调用类似于上述3所示的JScript方法的javascript方法。请记住,javascript的日期对象属性(涉及月份值)的编号范围是0到11,而不是1到12。所以9的值意味着10月。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <!-- : 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 --> 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(' '))); |
这里是alt.msdos.batch.nt的一个变体,它在本地独立工作。
将其放入文本文件中,例如getdate.cmd
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | -----------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"。但是,嘿,谁在乎呢!
我使用这个(同样不是地区独立(英国))。
1 | set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2% |
不幸的是,这不是免疫的区域设置,但它做你想要的。
1 2 3 | 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% |
你能在维基百科上找到的东西真是太棒了。
此代码的前四行将在Windows XP Professional及更高版本中为您提供可靠的YY-dd-mm-yy yy-hh-min-sec变量。
1 2 3 4 5 6 7 8 9 10 | @echo off for /f"tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set"dt=%%a" set"YY=%dt:~2,2%" & set"YYYY=%dt:~0,4%" & set"MM=%dt:~4,2%" & set"DD=%dt:~6,2%" set"HH=%dt:~8,2%" & set"Min=%dt:~10,2%" & set"Sec=%dt:~12,2%" set"datestamp=%YYYY%%MM%%DD%" & set"timestamp=%HH%%Min%%Sec%" & set"fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%" echo datestamp:"%datestamp%" echo timestamp:"%timestamp%" echo fullstamp:"%fullstamp%" pause |
请使用以下脚本在命令行中获取当前日期:
1 | echo %Date:~0,3%day |
另一种方式(信贷):
1 2 3 4 5 6 7 8 9 | @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% |
请注意,这里的两个答案仍然依赖于由区域设置确定的日期和月份顺序-不确定如何解决这个问题。
1 | "d:\Program Files\7-Zip\7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip |
这不是很简单,但可能是一种更灵活的方式(信贷):
1 2 3 4 5 | 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% |
以下是一种在一行中获取约会时间的方法:
1 | for /f"tokens=2,3,4,5,6 usebackq delims=:/" %a in ('%date% %time%') do echo %c-%a-%b %d%e |
在美国,将输出"年-月-日-时-分"。不同的区域设置将导致不同的%日期%输出,但您可以修改令牌顺序。
如果需要不同的格式,请通过重新排列标记或使用不同(或无)分隔符来修改echo语句。
只需使用这一行:
1 | PowerShell -Command"get-date" |
简短回答:
1 2 3 4 | :: 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 |
长回答
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | @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 |
这里有一个时间段的类似批处理文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | :: http://stackoverflow.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 time settings :: :: Gets the time in ISO 8601 24-hour format :: :: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that. :: Since ISO 8601 does not care about AM/PM, we use %time% :: @ECHO off SETLOCAL ENABLEEXTENSIONS for /f"tokens=1-4 delims=:,.-/" %%i in ('echo %time%') do ( set 'hh'=%%i set 'mm'=%%j set 'ss'=%%k set 'ff'=%%l) ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'% ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%] set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction% echo %timestring% :EOF |
——杰罗恩
我用vmax中的批处理文件更改了答案,因此它也适用于荷兰语。荷兰人——和我们一样坚持不懈——在破坏原始批处理文件的
如果有人也能对照其他Windows区域设置检查这个,并报告结果,那就太好了。如果批处理文件在您的位置失败,请在命令提示符中包含这两条语句的输出:
这是应从批处理文件中获得的输出示例:
1 2 3 | C:\temp>set-date-cmd.bat Today is Year: [2011] Month: [01] Day: [03] 20110103 |
下面是修订后的代码,其中有关于原因的注释:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | :: https://stackoverflow.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 [email protected] 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 |
——杰罗恩
MatthewJohnson的一行程序解决方案可以获得一行程序的日期和时间,这很有说服力,也很有用。
但是,它需要一个简单的修改才能在批处理文件中工作:
1 | for /f"tokens=2,3,4,5,6 usebackq delims=:/" %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e |
基于
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | :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。
用途:
1 2 | call:Now Y M D H N S echo %Y%-%M%-%D% %H%:%N%:%S% |
这会像这样回响一根弦:
1 | 2014-01-22 12:51:53 |
注意,函数参数是out参数——也就是说,必须提供变量名而不是值。
所有参数都是可选的,所以如果您只想获取年和月,那么
这是我用过的:
1 2 3 4 | ::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://witman.org/ziparcy/
http://sourceforge.net/projects/unxutils/files/文件/
在zip文件中查找"date.exe"并将其重命名为"dateformat.exe"(以避免冲突)。
将其放入Windows System32文件夹。
它有很多"日期输出"选项。
如需帮助,请使用
我不确定如何将其输出放入环境变量中…使用集合。
我也有类似的问题。我每天从一个FTP服务器上自动下载一个加密文件。我想用gpg解密文件,将文件重命名为当前日期(YYYYMMDD格式),然后将解密的文件放到正确部门的文件夹中。
我根据日期对文件进行了几次重命名建议,直到我偶然发现这个简单的解决方案,我才幸运。
1 | for /f"tokens=1-5 delims=/" %%d in ("%date%") do rename"decrypted.txt" %%g-%%e-%%f.txt |
它工作得很好(即,文件名显示为"2011-06-14.txt")。
(源)
生成ISO日期格式的区域独立解决方案:
1 2 3 4 5 6 7 8 | 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: |
仍然可以优化的内容:如果在修改日期格式时短时间内使用它,其他进程可能会感到困惑。因此,根据现有的格式字符串分析输出可能是"更安全的",但会更复杂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | :: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format :: - Sets environment variables %_isotime% and %_now% to current time :: - On failure, clears these environment variables :: Inspired on -> https://ss64.com/nt/syntax-getdate.html :: - (cX) 2017 [email protected] :: - http://stackoverflow.com/questions/203090 @echo off set _isotime= set _now= :: Check that WMIC.exe is available WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_ if not (%1)==() goto _help SetLocal EnableDelayedExpansion :: Use WMIC.exe to retrieve date and time FOR /F"skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO ( IF"%%~L"=="" goto _WMIC_done_ set _yyyy=%%L set _mm=00%%J set _dd=00%%G set _hour=00%%H set _minute=00%%I set _second=00%%K ) :_WMIC_done_ :: 1 2 3 4 5 6 :: %%G %%H %%I %%J %%K %%L :: Day Hour Minute Month Second Year :: 27 9 35 4 38 2017 :: Remove excess leading zeroes set _mm=%_mm:~-2% set _dd=%_dd:~-2% set _hour=%_hour:~-2% set _minute=%_minute:~-2% set _second=%_second:~-2% :: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep% :: Set date/time in ISO 8601 format: Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second% :: -> http://google.com/search?num=100&q=ISO+8601+format if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am if 1%_hour% LSS 112 goto _skip_12_ set /a _hour=1%_hour%-12 set _hour=%_hour:~-2% set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm :: -> https://ss64.com/nt/if.html :: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows :: 'if () else ()' will NOT set %_now% correctly !? :_skip_12_ EndLocal & set _isotime=%_isotime% & set _now=%_now% goto _out :_WMIC_MISSING_ echo. echo WMIC.exe command not available echo - WMIC.exe needs Administrator privileges to run in Windows echo - Usually the path to WMIC.exe is"%windir%\System32\wbem\WMIC.exe" :_help echo. echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format echo. echo %%_now%% environment variable set to current date and time echo %%_isotime%% environment variable to current time in ISO format echo set _today=%%_isotime:~0,10%% echo. :_out :: EOF: GetDate.cmd |
我更喜欢尽可能短的时间,所以没有月份和年份就足以进行每日更新。
1 2 3 4 5 6 7 8 9 | SET date=%DATE:~0,2% SET hour=%TIME:~0,2% SET minute=%TIME:~3,2% IF"%date:~0,1%"=="" SET date=0%DATE:~1,1% IF"%hour:~0,1%"=="" SET hour=0%TIME:~1,1% IF"%minute:~0,1%"=="" SET minute=0%TIME:~1,1% SET VERSION=%date%%hour%%minute% ECHO VERSION=%date%%hour%%minute% VERSION=140105 |
当涉及到应用程序的版本时,使用构建器部署新的每日更新
1 2 3 4 | steps: - name:"gcr.io/cloud-builders/gcloud" args: ["app","deploy", '--version=v1-140105-fresh'] timeout:"300s" |
这样,自动更新整个应用程序就更容易了。
1 2 | sed -e"s/-[0-9]\{1,\}-fresh/-%VERSION%-local/g" cloudbuild.yaml > tmp.txt mv -f tmp.txt cloudbuild.yaml |
输出文件将准备好进行本地更新,而无需触摸其文件名。
1 2 3 4 | steps: - name:"gcr.io/cloud-builders/gcloud" args: ["app","deploy", '--version=v1-140117-local'] timeout:"300s" |
给定一个已知的位置,以函数形式供参考。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | @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 |
保存到文件timestamp.bat,输出如下:
对于Windows 7,此代码适用于我:
1 2 3 4 5 6 7 8 9 10 | SET DATE=%date% SET YEAR=%DATE:~0,4% SET MONTH=%DATE:~5,2% SET DAY=%DATE:~8,2% ECHO %YEAR% ECHO %MONTH% ECHO %DAY% SET DATE_FRM=%YEAR%-%MONTH%-%DAY% ECHO %DATE_FRM% |
我知道已经提到了很多方法。但这是我分解它的方法来理解它是如何完成的。希望它对喜欢逐步方法的人有帮助。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | :: 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 |
我注意到O/P并没有要求区域独立的解决方案。不过,我的解决办法是在英国。
这是一种最简单的解决方案,一行解决方案,用于批处理文件:
1 2 | FOR /F"tokens=1-3 delims=/" %%A IN ("%date%") DO (SET today=%%C-%%B-%%A) echo %today% |