Note: Technical Talk being moved to:
www.nazimcricket.com/wiki


Tuesday, 19 August 2008

DOS - Append DateTime to Filename

In DOS, you can append the date/time to a filename as follows:

SET DAY=%DATE:~4,2%
SET MTH=%DATE:~7,2%
SET YR=%DATE:~10,4%
SET HR=%TIME:~0,2%
SET HR0=%TIME:~0,1%
IF "%HR0%"==" " SET HR=0%TIME:~1,1%
SET MIN=%TIME:~3,2%
SET SEC=%TIME:~6,2%
SET MYDATE=%YR%%MTH%%DAY%-%HR%%MIN%%SEC%
The above construct sets the date and time formats and can be adjusted according to whatever format is desired

The variable MYDATE can then be appended to the file as follows:

C:\dir > filename_%MYDATE%
Resulting in something like:
filename_20080819-165818

5 comments:

John said...

Hi Nazim, your script is very good. I was looking for a utility program to display the datetime and landed on your site. Your script is even better than what I was looking for because it uses the built-in DOS commands to form the filename as well. Thanks very much for sharing your knowledge! God bless you. :)

nazimcricket said...

You're welcome :)

Pedro said...

Thanks, very useful and clean!

Anonymous said...

Doesn't work .... on 2013/08/06 11:27:18
bat file output was:
SET DAY=8/
SET MTH=01
SET YR=
SET HR=11
SET HR0=1
IF "1" == " " SET HR=01
SET MIN=27
SET SEC=18
SET MYDATE=018/-112718

echo 018/-112718
018/-112718

this is clearly incorrect !

nazimcricket said...

Not sure if you're using this as it was meant to. It's a simple manipulation of the %DATE% function where:


% is used to enclose the expression

:~ is used to start the substring operation

1st Number is the index start point

2nd Number is the number of characters to extract