【问题标题】:How to append a date in batch files如何在批处理文件中附加日期
【发布时间】:2010-10-26 06:27:50
【问题描述】:

我在批处理文件中有以下行(在旧的 Windows 2000 盒子上运行):

7z a QuickBackup.zip *.backup

如何将日期附加到QuickBackup.zip 文件。因此,如果我今天运行批处理文件,理想情况下,该文件将是 QuickBackup20090514.zip

有没有办法做到这一点?

【问题讨论】:

  • 由于某些答案使用 %DATE% 环境变量,您可能希望让我们知道您的系统在“区域选项”控制面板中配置的“短日期格式”。
  • 一种独立于区域选项的方法是在an answer to Batch command date and time in file name - 基于系统命令wmic os get localdatetime /format:list。 wmic 的示例输出为:LocalDateTime=20140619215423.218000+120

标签: windows batch-file


【解决方案1】:

您也可以通过变量%DATE%访问日期

在测试我的系统时%DATE% 产生 ddd dd/mm/yyyy

您可以使用子字符串运算符来生成您想要的格式

即。使用美国区域设置在 2018 年 11 月 12 日星期一运行以下内容

%DATE:~3,3% %DATE:~0,3% %DATE:~7,2%

将产生一个输出:

11 Mon 12

子字符串参数是
%*variable*:~*startpos*,*numberofchars*%

【讨论】:

    【解决方案2】:

    这适用于非美国日期格式 (dd/MM/yyyy):

    set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%
    7z a QuickBackup%backupFilename%.zip *.backup
    

    【讨论】:

      【解决方案3】:

      如果您启用了WSL(仅限 Windows 10),您可以使用 bash 以区域设置中立的方式进行操作。

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

      请随意用此处和Windows batch assign output of a program to a variableWindows batch assign output of a program to a variable的其他答案中建议的“for”循环可憎替换文件重定向

      【讨论】:

        【解决方案4】:

        赛拉姆 使用上面给出的示例,我已经尝试并提出了我想要的脚本。其他例子中提到的位置参数给出了不同的结果。我想创建一个批处理文件来每天进行 Oracle 数据备份(导出数据),保留不同的 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%
        

        【讨论】:

        • 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 用户/密码文件=D:\DATA_DMP\%fn% Udayasankar/+91 9497648572
        【解决方案5】:

        基于 Joe 的想法,这里有一个版本,它将构建自己的 (.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%
        

        【讨论】:

          【解决方案6】:
          @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'
          

          【讨论】:

          • 这应该是公认的答案,因为它真正独立于语言环境!
          【解决方案7】:

          这一切都很尴尬,而且与本地设置无关。这样做:

          %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
          

          是的,使用Cygwin 日期,所有问题都解决了!

          【讨论】:

            【解决方案8】:

            Bernhard's answer 需要对我进行一些调整,因为 %DATE% 环境变量的格式不同(如在其他地方评论)。此外,还缺少一个波浪号 (~)。

            代替:

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

            我不得不使用:

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

            对于日期格式:

            c:\Scripts>回显 %DATE%

            2009 年 5 月 14 日星期四

            【讨论】:

            • 谢谢,我以完全相同的方式调整了我的文件,我看到了你的答案。
            • 克里斯,你错过了月份中的代字号应该是:set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE :~0,2%
            • 为了解析英国/欧盟/澳大利亚订单中的这种格式,我今天使用 set=%DATE:~10,4%%DATE:~7,2%%DATE:~4,2%
            • 这不适用于不同的机器,因为它们可能有不同的日期格式。
            • 这对我来说很完美,谢谢。像你一样,原来的答案没有用。我学到了一些关于在命令窗口中操作环境变量的知识!
            【解决方案9】:

            如前所述,仅当您知道当前用户使用的格式(例如,MM/dd/yy 或 dd-MM-yyyy 仅举个例子)时,解析日期和时间才有用。这是可以确定的,但是当你进行所有的重读和解析时,你仍然会遇到一些使用了意想不到的格式的情况,并且需要进行更多的调整。

            您也可以使用一些外部程序,以您喜欢的格式返回日期块,但缺点是需要将实用程序与您的脚本/批处理一起分发。

            还有一些以非常原始的方式使用 CMOS 时钟的批处理技巧,但对于大多数人来说这太接近裸线,而且并不总是检索日期/时间的首选位置。

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

            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
            

            【讨论】:

              【解决方案10】:

              我使用了这里介绍的环境变量技术: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.  E.g.,
              ::
              ::       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
              

              【讨论】:

              • 两个链接(在 cwashington.netreach.net 上)现在似乎都已损坏。你能修复链接吗?或者你有一些可以搜索的内容吗?
              【解决方案11】:

              我发现了两种无论日期设置如何都有效的方法。

              在我的电脑上,日期/t 返回 2009-05-27

              您可以访问注册表并读取区域设置 (HKEY_CURRENT_USER\控制面板\国际)

              或者使用 vbscript。 这是我前段时间创建的丑陋的批处理文件/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%
              

              它不漂亮,但它有效。

              【讨论】:

              • 无论日期设置如何,"date /t" 都不起作用。这取决于区域设置中的“短日期格式”。例如。如果设置为“dd-MM-yyyy”,则“date /t”返回例如“2009 年 9 月 25 日”。
              【解决方案12】:

              如果您知道您的区域设置不会改变,您可以按以下方式进行:

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

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

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

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

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

              我不建议将要在生产环境中使用的任何内容都依赖于区域设置。相反,您应该考虑使用另一种脚本语言 - PowerShell、VBScript...

              例如,如果您在与批处理文件相同的目录中创建具有以下内容的 VBS 文件 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)
              

              那么你就可以从你的批处理文件中调用它了:

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

              当然,最终会出现一种情况,即用更强大的脚本语言重写批处理文件比以这种方式将它与 VBScript 混合更有意义。

              【讨论】:

              • 第二个命令是关闭的,但我能够建立它。谢谢!!
              【解决方案13】:

              有一个可用的技术配方here 展示了如何将其格式化为 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”。我修复了它们,如果从这个页面剪切和粘贴,批处理文件将起作用。

              【讨论】:

              • 啊,下次我会在链接到另一个来源之前正确测试它。技术配方不起作用的原因是网页中的特殊引号字符。我更新了它,它现在可以工作了。
              【解决方案14】:

              当然。

              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
              

              【讨论】:

              • 如果这些都不起作用,请检查“区域和语言选项”控制面板。 %Date% 的日期格式取决于区域设置。
              猜你喜欢
              • 2015-03-23
              • 1970-01-01
              • 1970-01-01
              • 2015-08-09
              • 2011-05-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多