[windows] How to append a date in batch files

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 the QuickBackup.zip file. So if I ran the batch file today, ideally, the file would be QuickBackup20090514.zip.

Is there a way to do this?

This question is related to windows batch-file

The answer is


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.


There is a tech recipe available here that shows how to format it to MMDDYYYY, you should be able to adapt it for your needs.

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%

EDIT: The reason did not work before was because of 'smartquotes' in the original text. I fixed them and the batch file will work if cut & pasted from this page.


This will work for the non-US date format (dd/MM/yyyy):

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

Sure.

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

That is DDMMYYYY format.

Here's 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

As has been noted, parsing the date and time is only useful if you know the format being used by the current user (eg. MM/dd/yy or dd-MM-yyyy just to name 2). This could be determined, but by the time you do all the stressing and parsing, you will still end up with some situation where there is an unexpected format used, and more tweaks will be be necessary.

You can also use some external program that will return a date slug in your preferred format, but that has disadvantages of needing to distribute the utility program with your script/batch.

there are also batch tricks using the CMOS clock in a pretty raw way, but that is tooo close to bare wires for most people, and also not always the preferred place to retrieve the date/time.

Below is a solution that avoids the above problems. Yes, it introduces some other issues, but for my purposes I found this to be the easiest, clearest, most portable solution for creating a datestamp in .bat files for modern Windows systems. This is just an example, but I think you will see how to modify for other date and/or time formats, etc.

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

I've used the environment variables technique covered here: http://cwashington.netreach.net/depo/view.asp?Index=19

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

Here's the code from that site:

::~~Author~~.          Brett Middleton
::~~Email_Address~~. [email protected]
::~~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 <[email protected]>
::               :  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

Building on Joe's idea, here is a version which will build its own (.js) helper and supporting time as well:

@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 With the samples given above, I have tried & came out with the script which I wanted. The position parameters mentioned in other example gave different results. I wanted to create one Batch file to take the Oracle data backup (export data) on daily basis, preserving distinct DMP files with date & time as part of file name. Here is the script which worked well:

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%

If you have WSL enabled (Windows 10 only) you can do it with bash in a locale neutral way.

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

Feel free to replace the file redirection with a "for" loop abomination suggested in other answers here and over at Windows batch assign output of a program to a variable


This is all awkward and not local settings independent. Do it like this:

%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

Yes, use Cygwin date and all your problems are gone!


@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!' 

Output:

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

I've found two ways that work regardless of the date settings.

On my pc, date/t returns 2009-05-27

You can either access the registry and read the regional settings (HKEY_CURRENT_USER\Control Panel\International)

Or use a vbscript. This is the ugly batch file/vbscript hybrid I created some time ago....

@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%

It's not pretty, but it works.


You can also access the date via the variable %DATE%

When testing my system %DATE% produces ddd dd/mm/yyyy

you can use substring operators to produce the format you desire

ie. running the following on MON 11/12/2018 with US regional settings

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

Will produce an output:

11 Mon 12

the substring arguments are
%*variable*:~*startpos*,*numberofchars*%


Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to batch-file

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH Can´t run .bat file under windows 10 Execute a batch file on a remote PC using a batch file on local PC Windows batch - concatenate multiple text files into one How do I create a shortcut via command-line in Windows? Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat Curl not recognized as an internal or external command, operable program or batch file Best way to script remote SSH commands in Batch (Windows)