Date and time stamp in your batch files
There has been some activity recently in an old 2007 post I wrote about creating a date and time stamp in your batch files.
Well, the funny part was that I said ‘Date and Time’ in the subject, but I only talked about pulling out the current date.
Sue asked “What if I need both date, and time?”
Good question. What if you want to create a file that has the current date and time for each execution of the script?
In my old article I was creating zip files, using an imaginary command line based zip program. So in my article here I am going to make our goal to zip up a folder and name it:
YYYYMMDDHHMMSS_DATA.zip
If it were run today, our script should create a file by this name:
20091111143900_DATA.zip
To accomplish this, you need to use substring batch codes. If you want more detail on how these work, I explain it in the original article:
Create a date and time stamp in your batch files
To get the current time we use the %TIME% environment variable, and %DATE% for the date.
Using the substring batch codes from my old article, this is how we would pull out the year, month and day:
%date:~-4,4%%date:~-10,2%%date:~-7,2%
How about the time? That can be a little more difficult since the numbers returned from the time are not always the same length. For example, if it is 9 o’clock, it will say 9:00 – not 09:00. This will cause trouble when using the value for our filename.
Before we deal with that space, let me show you the substring codes to pull out the time:
Milliseconds: %time:~-2,2%
Seconds: %time:~-5,2%
Minutes: %time:~-8,2%
Hours: %time:~-11,2%
So naturally, if we wanted HHMMSS we could take those values above and put them side by side:
%time:~-11,2%%time:~-8,2%%time:~-5,2%
But like I said before, the hours can give you trouble because of the space. I came up with this code to pull off the space:
SET HOUR=%time:~-11,2%
Call :TRIM %HOUR%
GOTO :EOF
:TRIM
Set HOUR=%*
:EOF
REM You would use your trimmed hour right here
@echo %HOUR%
So, pulling it all together, how would we get an environment variable filled with a good date and time stamp filename?
Here is the code:
REM Get the hour first and put in an environment var
SET HOUR=%time:~-11,2%
Call :TRIM %HOUR%
GOTO :EOF
:TRIM
Set HOUR=%*
:EOF
REM Create our timestamp filename variable
SET DATESTMP=%date:~-4,4%%date:~-10,2%%date:~-7,2%%HOUR%
SET FILENAME=%DATESTMP%%time:~-8,2%%time:~-5,2%_DATA.ZIP
REM This is just an example call using our new filename
REM -=The real PKZIP program probably uses a different command line syntax
pkzip.exe c:\ImportantFolder\*.* c:\ZIPFILES\%FILENAME%
Using the code above, you can easily generate new files using the date and time in your batch script.
Written by Steve Wiseman on November 15th, 2009 with no comments.
Read more articles on BAT Files and Command Line and otherSoftware and Tools and Utility.
























