How can I append the date and time to a file?

John Savill

August 8, 2000

2 Min Read
ITPro Today logo

A. You can use the batch file below which will rename a file tofilename_YYYYMMDDHHMM.

@Echo OFF
TITLE DateName
REM DateName.CMD
REM takes a filename as %1 and renames as %1_YYMMDDHHMM
REM
REM -------------------------------------------------------------
IF %1.

. GoTo USAGE
Set CURRDATE=%TEMP%CURRDATE.TMP
Set CURRTIME=%TEMP%CURRTIME.TMP DATE /T > %CURRDATE%
TIME /T > %CURRTIME% Set PARSEARG="eol=; tokens=1,2,3,4* delims=/, "
For /F %PARSEARG% %%i in (%CURRDATE%) Do SET YYYYMMDD=%%l%%k%%j Set PARSEARG="eol=; tokens=1,2,3* delims=:, "
For /F %PARSEARG% %%i in (%CURRTIME%) Do Set HHMM=%%i%%j%%k Echo RENAME %1 %1_%YYYYMMDD%%HHMM%
RENAME %1 %1_%YYYYMMDD%%HHMM%
GoTo END :USAGE
Echo Usage: DateName filename
Echo Renames filename to filename_YYYYMMDDHHMM
GoTo END :END
REM
TITLE Command Prompt Example: D:Exchange> datetype logfile.log
RENAME logfile.log logfile.log_199809281630

Another method is as follows without temporary files. Also a leading zerois inserted for hour values below 10:

for /f "tokens=1,2" %%u in ('date /t') do set d=%%v
for /f "tokens=1" %%u in ('time /t') do set t=%%u
if "%t:~1,1%"

":" set t=0%t%
set timestr=%d:~6,4%%d:~3,2%%d:~0,2%%t:~0,2%%t:~3,2%
echo %timestr%

Other date options include LOGTIME.EXE which enables you to specify astring and then writes the time followed by the string to the filelogtime.log at the current default directory.

The other option is NOW.EXE which just replaces itself with the date andtime, e.g.

D:temp>now Batch complete
Mon Sep 28 15:54:19 1998 -- Batch complete

Both of the above utilities are part of the resource kit.

Another way is by using the following FOR command, a logfile can be created using real dates.

rem created unique log filename, e.g. Wed0804
    FOR /F "tokens=1-4 delims=/" %%i in ('date/t') do set file=%%i%%j%%k
    Set LOG=drive:directoryfilename-%file%.log

The result is a file named filename-date.log. Easier and works great!

You could also use

C:> net time >> file.txt

which also adds the time to the bottom of a file (but also has a successmessage so one of the other methods is better).

You can also use
Echo | more | time | find "current">>file.txt

Read more FAQs from John Savill.

Also, learn more from "Creating Date and Time Stamps."

About the Author(s)

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like