Home » Questions » Computers [ Ask a new question ]

Get custom date format in command in Windows 7

Get custom date format in command in Windows 7

I'm creating a backup script in a .bat file in Windows 7. As part of the script I create a log file. I'd like to create the log file with the following date format: YYYYDDMM_HH24MISS_backup.log

Asked by: Guest | Views: 205
Total answers/comments: 1
Guest [Entry]

"The other answer will choke when the month or hour are less than 10.

REM get a date time for a logfile name
REM If the echo %time% does not return a 24 hr time on the target OS / region settings,
REM You will need to do something like
REM set %ampm%=%time:~9,2%
REM if ""%ampm%"" EQU ""PM"" set /a hour=hour+12

REM testcase 1 with months, hours, mins, etc, less than 10.
REM Make sure to test with a format matches what your OS/regional settings will produce
REM test data should match the output from ""for /f ""tokens=1,2"" %%u in ('date /t') do set d=%%v""
REM and for /f ""tokens=1"" %%u in ('echo %time%') do set t=%%u

REM set d=01/02/2009
REM set t=3:04:05.06

REM testscase 2 with full width month, hours, mins, etc.
REM Make sure to test with a format matches what your OS/regional settings would produce in this case.

REM set d=10/20/2009
REM set t=10:20:30.40

REM if not testing, use the real date and time:
REM
REM the next line grabs the second (space) delimited thing from 'date /t', trims up spaces, and stores it in d
for /f ""tokens=1,2"" %%u in ('date /t') do set d=%%v
REM this times up the spaces from 'time'
for /f ""tokens=1"" %%u in ('echo %time%') do set t=%%u
if ""%t:~1,1%""=="":"" set t=0%t%

echo d has the value: ""%d%""
echo t has the value: ""%t%""

REM @echo off
set hour=%t:~0,2%
if ""%hour:~0,1%"" == "" "" set hour=0%hour:~1,1%
set min=%t:~3,2%
set secs=%t:~6,2%

set year=%d:~-4%
set month=%d:~0,2%
set day=%d:~3,2%

echo year=%year%,month=%month%,day=%day%,hour=%hour%,min=%min%,secs=%secs%

set datetimePartOfFile=%year%%day%%month%_%hour%24%min%%secs%
echo %datetimePartOfFile%

set filename=%datetimePartOfFile%_backup.log
echo %filename%

ren logfile.log %filename%

You can strip out a lot of it once you are sure it works, and have tested with months and hours less than 10, and your regional settings.

Here's the stripped down version without comments, or test cases:

Again, check that it works with your regional settings.

for /f ""tokens=1,2"" %%u in ('date /t') do set d=%%v
for /f ""tokens=1"" %%u in ('echo %time%') do set t=%%u
if ""%t:~1,1%""=="":"" set t=0%t%
set hour=%t:~0,2%
set min=%t:~3,2%
set secs=%t:~6,2%
set year=%d:~-4%
set month=%d:~0,2%
set day=%d:~3,2%
set datetimePartOfFile=%year%%day%%month%_%hour%24%min%%secs%
set filename=%datetimePartOfFile%_backup.log
ren logfile.log %filename%"