Subscribe to Windows IT Pro
August 27, 2003 12:00 AM

An Easier Way to Name Log Files with the Current Date and Time

Windows IT Pro
InstantDoc ID #39695
Rating: (3)
Downloads
39695.zip

Reader to Reader: "Automatically Name Log Files with the Current Date and Time" (February 2002, http://www.winnetmag.com, InstantDoc ID 23468) uses the Ntdate command, which is in Jeffery Harris's ANITX Toolset, to automatically name log files. However, Windows NT's Date and Time commands are more than adequate for this task.

I wrote the batch file that Listing 1 shows to create date- and time-specific logs. This batch file, which requires NT 4.0 or later with command-line extensions, sets several variables, including date (yyyymmdd), time of day (hhmmss), and timestamp (yyyymm-ddhhmmss-nn, where nn is hundredths of seconds). To timestamp records, you can run the code that Listing 2 shows to create a daily log file (yyyymmdd.log) and stamp each record with the time of day to 1-second accuracy (hhmmss). If you need multiple log files for the same day, you can replace the first three lines with

call GetTimeStamp mydate
echo %timestamp% log file 
%mydate%.log created. > 
%mydate%.log

to create a log file (yyyymmdd-hhmmss-nn.log) with date and timestamps to within 1/100 second.

To work on NT 4.0, GetTimeStamp.bat needs to trick the Time command into returning through the command

time <nul >~datetime.txt

Then, the batch file parses the first line of the output file. (The first For/f command could instead use Date/T, but the second can't use Time/T because Time/T displays time in a 12-hour clock format.)

Windows 2000 offers a more elegant solution. GetTimeStamp.bat can dispense with writing and reading ~datetime.txt and simply use the %time% and %date% environment variables. The For/f commands become

for /f "tokens=1-4 delims=/
 " %%i in ("%date%")
for /f "tokens=1-4 delims=.: 
" %%i in ("%time%")

Related Content:

ARTICLE TOOLS

Comments
  • Anonymous User
    7 years ago
    Jun 01, 2005

    Windows 2K offers a much more elegant solution by using variable substitution: just try this one:

    echo %date:/=%


  • Anonymous User
    7 years ago
    Jan 26, 2005

    Windows 2000 solution doesn't pad early hours with zeroes

  • delawhere
    8 years ago
    Dec 14, 2004

    Nice script ... I was looking to do something very similar, and you have got it all figured out already. Thanks.

You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement

advertisement

Windows is a trademark of the Microsoft group of companies. Windows IT Pro is used by Penton Media Inc. under license from owner.