Windows – Using Date and Times in a Batch File to Create a File Name

batch filedate timewindows

I am running a program from a batch file, which when it is done performs an automatic backup of my MySQL database.

I would like the batch file to create a different back up for each run, so I can backtrace.

The desired filename would be gnucash_shockwave-20121128210344.sql (Date format YYYY-MM-DD-HH-MM-SS)

I have googled a few things that said try %DATE:~4% and %Date.Year% but I get an error that says The system cannot find the specified path.

If I remove the attempt to timestamp it, the script works fine, but over writes the previous backup

Here is the section of code I'm talking about:

@REM *** EXECUTION ***
echo. Starting backup...
SET timestamp %DATE:~-4%%DATE:~4,2%%DATE:~7,2%%TIME%
%mysqldir%\mysqldump -u %mysqluser% -p%mysqlpassword% -h %mysqlhost% -P %mysqlport% --databases --routines --verbose gnucash_shockwave > %BackupDir%\gnucash_shockwave-%timestamp%.sql

echo.------------------------------------------------------
echo. Backup complete!

Any suggestions?

Best Answer

The Date and Time format depends on what you've specified in the Region and Language Control Panel applet.

Run the following batch file (which assumes dd/mm/yyyy and hh:mm:ss) and modify the substring extraction (using the : and ~ characters) as required to get the proper parts from both Date and Time strings:

@echo off
cls
echo Date format = %date%
echo dd = %date:~0,2%
echo mm = %date:~3,2%
echo yyyy = %date:~6,4%
echo.
echo Time format = %time%
echo hh = %time:~0,2%
echo mm = %time:~3,2%
echo ss = %time:~6,2%
echo.
echo Timestamp = %date:~6,4%-%date:~3,2%-%date:~0,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%

For more help on substring extraction, type set /? at the command prompt or see this page.

Related Question