Using Date and Times in a batch file to create a file name

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.


Here's what worked for me.

Format - mmddyyyy_HHMMSS

echo %DATE% %TIME%

Date format = Thu 03/05/2015 15:48:26.22

echo mm = %date:~4,2%

echo dd = %date:~7,2%

echo yyyy = %date:~10,4%

echo Timestamp = %date:~4,2%%date:~7,2%%date:~10,4%_%time:~0,2%%time:~3,2%%time:~6,2%

Timestamp - 03052015_154013

With a little tweaking I got this

@echo off
cls
echo Date format = %date%
echo dd = %date:~0,2%
echo mm = %date:~3,2%
echo yyyy = %date:~6,8%
echo.
echo Time format = %time%
echo hh = %time:~0,2%
echo mm = %time:~3,2%
echo ss = %time:~6,2%
echo.
echo Timestamp = %date:~0,2%_%date:~3,2%_%date:~6,8%-%time:~0,2%_%time:~3,2%_%time:~6,2%
ECHO "TEST..." > test-%date:~0,2%_%date:~3,2%_%date:~6,8%-%time:~0,2%_%time:~3,2%_%time:~6,2%.txt


Result:

"test-do_25_06-2015-22_21_51.txt" (Thursday_25th_June_2015-22:21.51)