DROTHISM

Adding timestamps in a DOS batch file

Posted by Drothism on Aug 5th, 2008

You would think that creating a timestamp for a filename (e.g., 20080208-1117.log) would be an easy thing to do since one of the most common things to do with batch commands is automating copy, create and rename file tasks.

I have tried all manner of scripts and third party solutions to attempt to generate a reliable timestamp for labelling files. Here is a fairly simple batch command solution to the problem. It takes the DOS date and time functions and splits the component parts into substrings.

@echo off
cls
rem Timestamp Generator

rem Parse the date (e.g., Fri 02/08/2008)
set cur_yyyy=%date:~10,4%
set cur_mm=%date:~4,2%
set cur_dd=%date:~7,2%

rem Parse the time (e.g., 11:17:13.49)
set cur_hh=%time:~0,2%
if %cur_hh% lss 10 (set cur_hh=0%time:~1,1%)
set cur_nn=%time:~3,2%
set cur_ss=%time:~6,2%
set cur_ms=%time:~9,2%

rem Set the timestamp format
set timestamp=%cur_yyyy%%cur_mm%%cur_dd%-%cur_hh%%cur_nn%%cur_ss%%cur_ms%

rem Do something with it
echo Timestamp: %timestamp%

rem Clear the environment variables
set cur_yyyy=
set cur_mm=
set cur_dd=
set cur_hh=
set cur_nn=
set cur_ss=
set cur_ms=
set timestamp=

The caveat is that it depends on the format of the date and time on your computer which are defined by the regional settings in the Control Panel. If the substrings don’t have the required information in them you may need to tweak the substring positions to suit your date and time settings.

Leave a reply

You must be logged in to post a comment.