如何在batch file中附加date

我在batch file(在旧的Windows 2000框上运行)中有以下行:

7z a QuickBackup.zip *.backup 

如何将date附加到QuickBackup.zip文件。 所以,如果我今天运行batch file,理想情况下,该文件将是QuickBackup20090514.zip

有没有办法做到这一点?

Bernhard的回答需要一些调整,因为%DATE%环境variables的格式不同(正如其他地方所述)。 还有一个波浪号(〜)缺失。

代替:

set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:0,2%

我不得不使用:

set backupFilename=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%

对于date格式:

c:\ Scripts> echo%DATE%

星期四05/14/2009

如果你知道你的区域设置不会改变,你可以这样做:

  • 如果您的短date格式是dd / MM / yyyy:

    SET MYDATE =%DATE:〜3,2 %%date:〜0.2%date:〜8.4%

  • 如果您的短date格式是MM / dd / yyyy:

    SET MYDATE =%DATE:〜0,2 %% DATE:〜3,2 %% DATE:〜8,4%

但是没有一个通用的方法可以独立于您的区域设置。

我不build议依靠区域设置来生产环境中的任何东西。 相反,你应该考虑使用另一种脚本语言 – PowerShell,VBScript,…

例如,如果您在batch file所在的同一目录下创buildVBS文件yyyymmdd.vbs ,其中包含以下内容:

 ' yyyymmdd.vbs - outputs the current date in the format yyyymmdd Function Pad(Value, PadCharacter, Length) Pad = Right(String(Length,PadCharacter) & Value, Length) End Function Dim Today Today = Date WScript.Echo Pad(Year(Today), "0", 4) & Pad(Month(Today), "0", 2) & Pad(Day(Today), "0", 2) 

那么你将能够从你的batch file调用它:

 FOR /F %%i IN ('cscript "%~dp0yyyymmdd.vbs" //Nologo') do SET MYDATE=%%i echo %MYDATE% 

当然,最终会出现这样一种情况:以更强大的脚本语言重写batch file比以这种方式将其与VBScript混合更有意义。

 set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2% 7z a QuickBackup%backupFilename%.zip *.backup 
 @SETLOCAL ENABLEDELAYEDEXPANSION @REM Use WMIC to retrieve date and time @echo off FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO ( IF NOT "%%~F"=="" ( SET /A SortDate = 10000 * %%F + 100 * %%D + %%A set YEAR=!SortDate:~0,4! set MON=!SortDate:~4,2! set DAY=!SortDate:~6,2! @REM Add 1000000 so as to force a prepended 0 if hours less than 10 SET /A SortTime = 1000000 + 10000 * %%B + 100 * %%C + %%E set HOUR=!SortTime:~1,2! set MIN=!SortTime:~3,2! set SEC=!SortTime:~5,2! ) ) @echo on @echo DATE=%DATE%, TIME=%TIME% @echo HOUR=!HOUR! MIN=!MIN! SEC=!SEC! @echo YR=!YEAR! MON=!MON! DAY=!DAY! @echo DATECODE= '!YEAR!!MON!!DAY!!HOUR!!MIN!' 

输出:

 DATE=2015-05-20, TIME= 1:30:38.59 HOUR=01 MIN=30 SEC=38 YR=2015 MON=05 DAY=20 DATECODE= '201505200130' 

这是所有的尴尬,而不是本地设置独立。 像这样做:

 %CYGWIN_DIR%\bin\date +%%Y%%m%%d_%%H%%M% > date.txt for /f "delims=" %%a in ('type "date.txt" 2^>NUL') do set datetime=%%a echo %datetime% del date.txt 

是的,使用Cygwindate,所有的问题都消失了!

当然。

 FOR %%A IN (%Date:/=%) DO SET Today=%%A 7z a QuickBackup%TODAY%.zip *.backup 

这是DDMMYYYY格式。

这是YYYYDDMM:

 FOR %%A IN (%Date%) DO ( FOR /F "tokens=1-3 delims=/-" %%B in ("%%~A") DO ( SET Today=%%D%%B%%C ) ) 7z a QuickBackup%TODAY%.zip *.backup 

您也可以通过variables%DATE%访问date

在testing我的系统时, %DATE%产生dd / mm / yyyy

你可以使用子string运算符来产生你想要的格式

 %DATE:~3,2%%DATE:~0,2%%DATE:~6,4% 

子string是
%*variable*:~*startpos*,*numberofchars*%

这里有一个技术配方,显示如何格式化为MMDDYYYY,你应该能够适应你的需求。

 echo on @REM Seamonkey's quick date batch (MMDDYYYY format) @REM Setups %date variable @REM First parses month, day, and year into mm , dd, yyyy formats and then combines to be MMDDYYYY 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% echo %date% 

编辑:原因之前没有工作是因为在原文中的“smartquotes”。 我修复它们,batch file将工作,如果从这个页面剪切和粘贴。

我已经使用了这里涵盖的环境variables技术: http : //cwashington.netreach.net/depo/view.asp?Index=19

http://cwashington.netreach.net/depo/default.asp?topic=repository&move=last&ScriptType=command&SubType=Misc

以下是该网站的代码:

 ::~~Author~~. Brett Middleton ::~~Email_Address~~. brettm@arches.uga.edu ::~~Script_Type~~. nt command line batch ::~~Sub_Type~~. Misc ::~~Keywords~~. environment variables ::~~Comment~~. ::Sets or clears a group of environment variables containing components of the current date extracted from the string returned by the DATE /T command. These variables can be used to name files, control the flow of execution, etc. ::~~Script~~. @echo off ::----------------------------------------------------------------------------- :: SetEnvDate1.CMD 6/30/98 ::----------------------------------------------------------------------------- :: Description : Sets or clears a group of environment variables containing :: : components of the current date extracted from the string :: : returned by the DATE /T command. These variables can be :: : used to name files, control the flow of execution, etc. :: : :: Requires : Windows NT with command extensions enabled :: : :: Tested : Yes, as demonstration :: : :: Contact : Brett Middleton <brettm@arches.uga.edu> :: : Animal and Dairy Science Department :: : University of Georgia, Athens ::----------------------------------------------------------------------------- :: USAGE :: :: SetEnvDate1 can be used as a model for coding date/time routines in :: other scripts, or can be used by itself as a utility that is called :: from other scripts. :: :: Run or call SetEnvDate1 without arguments to set the date variables. :: Variables are set for the day abbreviation (DT_DAY), month number (DT_MM), :: day number (DT_DD) and four-digit year (DT_YYYY). :: :: When the variables are no longer needed, clean up the environment by :: calling the script again with the CLEAR argument. Eg, :: :: call SetEnvDate1 clear ::----------------------------------------------------------------------------- :: NOTES :: :: A time variable could be added by parsing the string returned by the :: built-in TIME /T command. This is left as an exercise for the reader. B-) :: :: This script illustrates the following NT command extensions: :: :: 1. Use of the extended IF command to do case-insensitive comparisons. :: :: 2. Use of the extended DATE command. :: :: 3. Use of the extended FOR command to parse a string returned by a :: command or program. :: :: 4. Use of the "()" conditional processing symbols to group commands :: for conditional execution. All commands between the parens will :: be executed if the preceeding IF or FOR statement is TRUE. ::----------------------------------------------------------------------------- if not "%1" == "?" goto chkarg echo. echo Sets or clears date/time variables in the command environment. echo. echo SetEnvDate1 [clear] echo. echo When called without arguments, the variables are created or updated. echo When called with the CLEAR argument, the variables are deleted. echo. goto endit ::----------------------------------------------------------------------------- :: Check arguments and select SET or CLEAR routine. Unrecognized arguments :: are ignored and SET is assumed. ::----------------------------------------------------------------------------- :chkarg if /I "%1" == "CLEAR" goto clrvar goto setvar ::----------------------------------------------------------------------------- :: Set variables for the day abbreviation (DAY), month number (MM), :: day number (DD) and 4-digit year (YYYY). ::----------------------------------------------------------------------------- :setvar for /F "tokens=1-4 delims=/ " %%i IN ('date /t') DO ( set DT_DAY=%%i set DT_MM=%%j set DT_DD=%%k set DT_YYYY=%%l) goto endit ::----------------------------------------------------------------------------- :: Clear all variables from the environment. ::----------------------------------------------------------------------------- :clrvar for %%v in (DT_DAY DT_MM DT_DD DT_YYYY) do set %%v= goto endit :endit 

如前所述,parsingdate和时间只有在您知道当前用户正在使用的格式时才有用(例如,MM / dd / yy或dd-MM-yyyy只是为了命名2)。 这可以被确定,但是当你做所有的压力和parsing的时候,你仍然会遇到一些意外格式的使用,而且需要更多的调整。

您也可以使用一些外部程序,它会以您的首选格式返回一个date段落,但是这样做有缺点,需要使用脚本/批处理来分发实用程序。

也有一些使用CMOS时钟的批量技巧,但对于大多数人来说,这种技术太靠近裸线了,并不总是首选检索date/时间的地方。

以下是避免上述问题的解决scheme。 是的,它引入了一些其他问题,但为了我的目的,我发现这是在现代Windows系统的.bat文件中创builddate戳的最简单,最清晰,最便携的解决scheme。 这只是一个例子,但我想你会看到如何修改其他date和/或时间格式等。

 reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f reg add "HKCU\Control Panel\International" /v sShortDate /d "yyMMdd" /f @REM the following may be needed to be sure cache is clear before using the new setting reg query "HKCU\Control Panel\International" /v sShortDate set LogDate=%date% reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f 

我发现有两种方法可以工作,无论date设置如何。

在我的电脑上,date/吨返回2009-05-27

您可以访问registry并阅读区域设置(HKEY_CURRENT_USER \ Control Panel \ International)

或者使用一个VBScript。 这是我前段时间创build的丑陋的batch file/ VBScript混合。

 @Echo Off set rnd=%Random% set randfilename=x%rnd%.vbs ::create temp vbscript file Echo Dim DayofWeek(7) > %temp%\%randfilename% Echo DayofWeek(1)="Sun" >> %temp%\%randfilename% Echo DayofWeek(2)="Mon" >> %temp%\%randfilename% Echo DayofWeek(3)="Tue" >> %temp%\%randfilename% Echo DayofWeek(4)="Wed" >> %temp%\%randfilename% Echo DayofWeek(5)="Thu" >> %temp%\%randfilename% Echo DayofWeek(6)="Fri" >> %temp%\%randfilename% Echo DayofWeek(7)="Sat" >> %temp%\%randfilename% Echo DayofWeek(0)=DayofWeek(Weekday(now)) >> %temp%\%randfilename% Echo Mon=Left(MonthName(Month(now),1),3) >> %temp%\%randfilename% Echo MonNumeric=right ( "00" ^& Month(now) , 2) >> %temp%\%randfilename% Echo wscript.echo ( Year(Now) ^& " " ^& MonNumeric ^& " " ^& Mon ^& " " _ >> %temp%\%randfilename% Echo ^& right("00" ^& Day(now),2) ^& " "^& dayofweek(0) ^& " "^& _ >> %temp%\%randfilename% Echo right("00" ^& Hour(now),2)) _ >> %temp%\%randfilename% Echo ^&":"^& Right("00" ^& Minute(now),2) ^&":"^& Right("00" ^& Second(Now),2) >> %temp%\%randfilename% ::set the output into vars if "%1" == "" FOR /f "usebackq tokens=1,2,3,4,5,6" %%A in (`start /wait /b cscript //nologo %temp%\%randfilename%`) do Set Y2KYear=%%A& Set MonthNumeric=%%B& Set Month=%%C& Set Day=%%D& Set DayofWeek=%%E& Set Time=%%F set year=%y2kyear:~2,2% ::cleanup del %temp%\%randfilename% 

这不是很漂亮,但它的工作原理。

基于Joe的想法,下面是一个将自己构build( .js )帮手和支持时间的版本:

 @echo off set _TMP=%TEMP%\_datetime.tmp echo var date = new Date(), string, tmp;> "%_TMP%" echo tmp = ^"000^" + date.getFullYear(); string = tmp.substr(tmp.length - 4);>> "%_TMP%" echo tmp = ^"0^" + (date.getMonth() + 1); string += tmp.substr(tmp.length - 2);>> "%_TMP%" echo tmp = ^"0^" + date.getDate(); string += tmp.substr(tmp.length - 2);>> "%_TMP%" echo tmp = ^"0^" + date.getHours(); string += tmp.substr(tmp.length - 2);>> "%_TMP%" echo tmp = ^"0^" + date.getMinutes(); string += tmp.substr(tmp.length - 2);>> "%_TMP%" echo tmp = ^"0^" + date.getSeconds(); string += tmp.substr(tmp.length - 2);>> "%_TMP%" echo WScript.Echo(string);>> "%_TMP%" for /f %%i in ('cscript //nologo /e:jscript "%_TMP%"') do set _DATETIME=%%i del "%_TMP%" echo YYYYMMDDhhmmss: %_DATETIME% echo YYYY: %_DATETIME:~0,4% echo YYYYMM: %_DATETIME:~0,6% echo YYYYMMDD: %_DATETIME:~0,8% echo hhmm: %_DATETIME:~8,4% echo hhmmss: %_DATETIME:~8,6% 

Sairam根据上面给出的样本,我尝试了一下我想要的脚本。 其他例子中提到的位置参数给出了不同的结果。 我希望创build一个batch file,以便每天进行Oracle数据备份(导出数据),将date和时间不同的DMP文件保留为文件名的一部分。 下面是运行良好的脚本:

 cls set dt=%date:~0,2%%date:~3,2%%date:~6,4%-%time:~0,2%%time:~3,2% set fn=backup-%dt%.DMP echo %fn% pause A exp user/password file=D:\DATA_DMP\%fn% 

如果您启用了WSL (仅适用于Windows 10),则可以使用bash以中性语言环境进行操作。

 set dateFile=%TEMP%\currentDate.txt bash -c "date +%Y%m%d" > %dateFile% set /p today=<%dateFile% 

随意使用在这里和其他答案中build议的“for”循环憎恶取代文件redirect在Windows批处理分配一个程序的输出到一个variables