Get the Network Administrators tool pack

Subscribe to our newsletter and get 11 free network administrator tools, plus a 30 page user guide so you can get the most out of them.

Click Here to get your free tools

Recent Posts



Create a date and time stamp in your batch files

by Steve Wiseman on February 16, 2007 · 43 comments

in Windows


Here is an interesting one. I found a way to take the %date% environment variable, and turn it into a valid string for a filename – without any extra programs or scripts.

For the longest time I used a little utility I created to do this. The problem with that is the utility needs to be around if you want to send the batch file to someone.

What I didn’t know that was that you can use this character combination ‘:~’ to pull a substring out of an environment variable. That is when I realized you could use this to pull out parts of the current date (or time).

Here is how it works. Lets take the %date% variable and print it out

echo %date%

It comes back …At least today ;) .. with

Thu 02/15/2007

Not sure if the length of the day changes. It may be always the same. To be safe we can pull the year, month and day starting from the right.

The :~ substring command works like this:


If [START_POS] is positive or zero the substring will start from the left. If the number [START_POS] is negative it will start from the right. And [LENGTH] is the number of characters in the opposite direction of the starting point.

I know this might be confusing at first, but you will see what I am talking about.

If we wanted to get the current year we could start 4 from the end, and 4 in length. Like this:

echo %date:~-4,4%

For the month we start 7 from the right (Length of Year + Length of Month + 1 Slash)

echo %date:~-7,2%

For the day we start 10 from the right (Length of Year + Length of Month + Length Of Day + 2 Slashes)

echo %date:~-10,2%

Bringing it all together. Lets say I zipped up a folder every night for archival purposes, and wanted a different filename for each day (Not sure if this pkzip syntax is correct, but that is not important for our discussion here)

pkzip c:\ImportantFolder\*.* c:\
ren C:\TempZip.Zip c:\TempZip_%date:~-4,4%%date:~-7,2%%date:~-10,

Which renames our C:\TempZip.Zip to C:\

Perfect. I get a date stamped file, and no special vbscript, or command line program is needed.

The same method could be used for the current time

I am still amazed this little trick works.

One more thing…Subscribe to my newsletter and get 11 free network administrator tools, plus a 30 page user guide so you can get the most out of them. Click Here to get your free tools

Related Articles:

{ 1 trackback }

Date and time stamp in your batch files
November 11, 2009 at 3:23 pm

{ 42 comments… read them below or add one }

1 John October 14, 2009 at 1:43 pm

Working Fine……..

2 date *and* time October 28, 2009 at 9:11 am

here’s the “and time” bit:

I know it might sound obvious, but…
…….for time, use environment variable %time%

3 Steve Wiseman October 28, 2009 at 9:34 am

Good point. Title did not match my article. You can use the same principals with the time variable, and include hours, minutes, seconds, and milliseconds.

Here they are:

Milliseconds: %time:~-2,2%
Seconds: %time:~-5,2%
Minutes: %time:~-8,2%
Hours: %time:~-11,2%

4 Lizzy November 2, 2009 at 1:10 am


Thanks, These are very helpful tips.

The problen is that when retrieving the hour from the current time variable,
it appears with a leading space (instead of leading zero), when the hour is less than 10.

Any idea to solve it?


5 Steve Wiseman November 2, 2009 at 8:23 am

Here is the way to trim it:

SET HOUR=%time:~-11,2%
Set HOUR=%*
REM You would use your trimmed hour right here
@echo %HOUR%

6 Jim November 12, 2009 at 3:51 pm

fyi: the below line should be changed

from this: DATESTMP=%date:~-4,4%%date:~-7,2%%date:~-10,2%%HOUR% SET

swap 10,2 and 8,2 (date to be y/m/d)
insert :TRIM (else blank between hour and rest (m/s_DATA.ZIP)

to this: DATESTMP=%date:~-4,4%%date:~-10,2%%date:~-7,2%%HOUR% :TRIM SET

Great concept. thanks.

7 Steve Wiseman November 12, 2009 at 7:22 pm

What format is your date in DD/MM/YYYY or MM/DD/YYYY…when you echo %date% at the command line?


8 bryan December 28, 2009 at 11:07 pm

Hi Guys,

i am newbie in the Batch file creation and hoping you guys can help and guide me on the following:-

i wanted to created a batch file to :-
1st – zip a folder containing a txt files
2nd – the batch file shall ignore the current date folder
3rd – the batch shall be executed on 1200am daily.
4th – the zipped folder name should retained
5th – once the folder has been zipped, it will be move to a dedicated folder (to another HDD or even to a network folder)

By the way, i am using power archiver 2001.

Thank you in advance..

9 Israel Torres August 19, 2010 at 10:49 am

@Lizzie – perhaps a little late but here’s how I ended up doing the leading space issue for the time :)

set tmp_time=%time:~-11,2%%time:~-8,2%%time:~-5,2%
:: method 1 use this to trim leading space entirely
::set tmp_time=%tmp_time: =%

:: method 2 use this to replace leading space with 0
set tmp_time=%tmp_time: =0%

@ Steve W. – Thanks!

Israel Torres

10 Bewc September 22, 2010 at 9:20 pm


Thanks you for the article! Here’s my take… I like double digit hours, so the trim doesn’t work for me. I think it makes it harder visually and in script to parse.

Here are how I break down my variables (not all of them are used in a given script):

set year=%date:~-4,4%
set month=%date:~-10,2%
set day=%date:~-7,2%
set hourMilitary=%time:~-11,2%

::::: identify hours in Civilian time, and identify AM or PM
for /f “tokens=1-2*” %%t in (‘time /t’) do (
set twelvehourtime=%%t
set AMPM=%%u

set hourCivilian=%twelvehourtime:~0,2%

::::: I like my hours double digit
if “%AMPM%” == “AM” set hourMilitary=%hourCivilian%

set minute=%time:~-8,2%
set second=%time:~-5,2%
set millisecond=%time:~-2,2%

::::: identify Name of the day and provide short date for today
for /f “tokens=1-2*” %%v in (‘date /t’) do (
set dayName=%%v
set todaysdate=%%w

set datetimestamp=%year%%month%%day%%hour%%minute%%second%

::::: demonstrate math abilities of “set /a” by getting yesterday’s number
set /a TODAYminus1=%day%-1

::::: then do something practical, like query for the last 24 hours of event logs
set yesterdaysstamp=%month%/%TODAYminus1%/%year%,%hourCivilian%:%minute%:%second%%AMPM%

echo year is %year%
echo month is %month%
echo day is %day%
echo hourMilitary is %hourMilitary%
echo hourCivilian is %hourCivilian%
echo AMPM is %AMPM%
echo minute is %minute%
echo second is %second%
echo millisecond is %millisecond%
echo dayName is %dayName%
echo todaysdate is %todaysdate%
echo datetimestamp is %datetimestamp%
echo TODAYminus1 is %TODAYminus1%
echo %yesterdaysstamp%

eventquery /l application /v /fo list /fi “Datetime gt %yesterdaysstamp%” >> d:\%datetimestamp%_last24hourslogs.txt

I’m hoping someone finds this useful, so I know I gave back.

Thanks again!


11 MGnP September 23, 2010 at 11:47 am


Excellent. Thank you very much, this is exactly what I was looking for.

12 Tom Summers October 5, 2010 at 2:49 pm

Thanks Steve, we’ve been fighting the time thing all morning. This helps alot. Again thanks

13 Roger February 14, 2011 at 8:25 pm

It seems to me that I have seen quite a similar example in the setup package of Dr.Batcher ( ). This is an utility to create batch files, and it’s extremely useful.

14 brijesh May 16, 2011 at 11:47 am

Hey guys,

could someone help me in displaying current timestamp.

i tried
%date:~-4,4%/%date:~-7,2%/%date:~-10,2% %time:~-11,2%:%time:~-8,2%:%time:~-5,2%

but its quite long and putting it in a variable then displaying the variable show the time when i set that variable.

please let me know how should i use that variable to show the current date and time


15 Aidan July 8, 2011 at 6:48 am

I hate windows so thanks to all above for doing the hard work me! Very usefu, thanks again.


16 Steve Wiseman July 8, 2011 at 9:38 am

Glad to help Aidan. Thanks for taking the time to comment – Steve

17 Bill July 27, 2011 at 2:09 am

Hi All!!!
Thanks for ALL the GREAT ideas!
I wanted to know how I can get the timestamp of a FILE to echo in a batch, rather than just the system time.
I am FTPing a file once a minute from a camera server, and sometimes the server hangs and doesn’t update the image, so the time stamp doesn’t change.
I wanted to be able to see the image’s timestamp displayed while my batch is running.
Any ideas? (I am using a simple command (DOS) window and a batch file that displays all FTP activity, EXCEPT the file’s timestamp).

18 anon August 22, 2011 at 5:53 pm

Create a filename with Date and Time stamp, cleanly.

SET CurrentDate=%date:~-4,4%%date:~-7,2%%date:~-10,2%
SET CurrentTIme=%time:~-11,2%%time:~-8,2%%time:~-5,2%

echo c:\%CurrentDate%_T%CurrentTime%.csv

19 Smari September 20, 2011 at 9:17 am

Thanks a lot Steve. that was very helpful.

20 Joel November 18, 2011 at 6:26 pm

This was a great, simple solution. And thanks to other posters, who added the code to get the Hours, Minutes, Seconds.

21 Derek Morin December 23, 2011 at 10:21 am

Awesome code Bewc!! That is really fantastic and you obviously put a lot of effort into it.

In case others hit an error:

I hit error with using this code, but it turned out the that double quote and single quote characters didn’t paste well from the website, and I just needed to change them on the two “for” loop lines.

I also added @echo off at the top of the batch file to just see the output.

22 Waschtrommel April 26, 2012 at 3:44 am

@anon: Very helpfil hint.

For those who want to shift output into a variable, you should try FOR /F:

For /F %%i in (‘date /t’) Do @set CURRENTDATE=%%i

If anyone has to do date calculations (f.e. relative to now or calculate the date of next tuesday etc…) a very helpful GNU-Tool was compiled for windows: gdate.exe (see google).

Example (take note for double percentage signs in batches):
for /F “usebackq” %%a in (`gdate.exe +%%Y%%m%%d-%%H%%M`) do set NOW=%%a

%NOW% should result in something like 20120426-0930

for /F “usebackq” %%a in (`gdate.exe –date=+1day +%%d.%%m.%%Y`) do set TOMORROW=%%a

calculates ‘tomorrow’ (word! i.e. Monday)

for /F “usebackq” %%a in (`gdate.exe –date=+1day +%%w`) do set DAYOFTOMORROW=%%a

Have a lot of fun


23 Waschtrommel April 26, 2012 at 4:24 am


for /F “usebackq” %%a in (`gdate.exe –date=+1day +%%d.%%m.%%Y`) do set TOMORROW=%%a

calculates ‘tomorrow’ (German notation 27.04.2012)

for /F “usebackq” %%a in (`gdate.exe –date=+1day +%%w`) do set DAYOFTOMORROW=%%a

calculates ‘dayoftomorrow’ (word! i.e. Monday)

24 Waschtrommel April 26, 2012 at 5:52 am

…see GNU Tools for Windows – date.exe

25 Steve Wiseman April 26, 2012 at 8:36 am

Thanks for the post Waschtrommel! Very helpful stuff.

26 Daniel Castellanos April 30, 2012 at 9:41 am

I tried your example of changing the directory tempzip to one with a time stamp and received the error “the syntax of the command is incorrect. would like to send you a screenshot, but don’t know where to send it. I know it has to work, but it’s something I’m missing. Thanks for the help!

27 Steve Wiseman May 4, 2012 at 11:42 am

Just send something to and I will take a look at it for you.


28 Amil June 15, 2012 at 5:40 pm

Nice. Thanks for the guide!
I implemented this in my one-click backup .bat file for the source code at my work.

29 Carlos Echegaray July 22, 2012 at 11:26 pm

Hi there, i use this code to get the date and time stamp, hope it helps:

echo off

echo Running…

rem date, time

set varYear=%date:~-4,4%
set varMonth=%date:~-7,2%
set varDay=%date:~-10,2%

set varHour=%time:~-11,2%

if %varHour% leq 9 (
call :trim %varHour%
goto :eof
set varHour=0%*

set varMinutes=%time:~-8,2%

rem filename

set varFileName=Filename_%varYear%%varMonth%%varDay%_%varHour%%varMinutes%.txt

echo %varFileName%


30 Scott Blaydes September 23, 2012 at 8:44 am

Thanks for the post Steve. Thanks to everyone else, as the comments are getting to be about as useful as the original post for my needs.

31 Paul W. October 6, 2012 at 11:41 am

Knowledge…the gift that keeps on giving. This is the only place I’ve been able to find that so clearly explains the use of the date and time variable in renaming files in a script (I’ve looked at a lot of sites). Thank you Steve (and all the other contributors). This is an excellent discussion.

32 Steve Wiseman October 6, 2012 at 3:33 pm

Thank you for the kind words Paul. Really appreciate it :)


33 Paul October 29, 2012 at 10:53 am

Works fine except it depends heavily on national date format outputted by %date%

34 Steve Wiseman October 29, 2012 at 9:16 pm

Very true Paul. Too bad there is not an easier way to do this via a bat file.

35 Sun November 12, 2012 at 11:26 pm

Didn’t know your sample was YYYYDDMM format not what I was expecting… YYYYMMDD — easy enough to fix. :)

36 Art K December 18, 2012 at 5:00 pm

FYI The format of the date (delimiter, order, sizes, content), is set/customized by the Regional and Language Settings in the Control panel:

Cntl Pnl | Regional | Customize | Date

ddd MMM dd,yyyy

is the template for the format you show.

However, your %date% is returning the long date format, mine is returning the short date farmat. Not sure yet what is going on.

37 parto April 11, 2013 at 5:18 am

anon, perfect :D

38 Sidk April 17, 2013 at 9:37 am

Thanks for the info. We just finished testing this in Windows 7 and it worked just fine, still.

39 Sidk April 17, 2013 at 2:37 pm

We just finished testing this neat trick with Windows 8, 64 bit, and had no problem.

40 Trey May 21, 2013 at 3:00 pm

I ran your script and everything works fine, as long as its not the first of the month. today is 5-21-2013. If I change “set /a TODAYminus1=%day%-1″ to “set /a TODAYminus1=%day%-25″
The final output says 05/-4/2013,11:51:49AM.
How do we handle traveling across months and years?
This would be great for purging old file backups!


41 Gody August 1, 2013 at 9:48 am

The substring’ing I see going on here won’t work on windows systems which have a different date/time style set through the control panel. (as Art K also already mentioned). Please note that scripts using your code might not generate similar results on other peoples’ systems. Use a PowerShell script to have more control over your date and time usage (

42 Apeksha September 27, 2014 at 5:01 am

Hi All,

My query is :

Is it possible to display the time stamp of the last created file eg. file1.txt.
and then to read files that come after that file1.txt

here name of the file vary based on the condition.

Leave a Comment

Category Links - Windows Forum - Exchange Forum