How to append a date in batch files

后端 未结 14 2191
夕颜
夕颜 2020-12-01 03:25

I have the following line in a batch file (that runs on an old Windows 2000 box):

7z a QuickBackup.zip *.backup

How do I append the date to

14条回答
  •  旧时难觅i
    2020-12-01 04:14

    If you know your regional settings won't change you can do it as follows:

    • if your short date format is dd/MM/yyyy:

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

    • if your short date format is MM/dd/yyyy:

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

    But there's no general way to do it that's independent of your regional settings.

    I would not recommend relying on regional settings for anything that's going to be used in a production environment. Instead you should consider using another scripting language - PowerShell, VBScript, ...

    For example, if you create a VBS file yyyymmdd.vbs in the same directory as your batch file with the following contents:

    ' 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)
    

    then you will be able to call it from your batch file thus:

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

    Of course there will eventually come a point where rewriting your batch file in a more powerful scripting language will make more sense than mixing it with VBScript in this way.

提交回复
热议问题