Using timestamps in batch files
After failing many times before, I have finally found out how to create user-friendly timestamps in batch scripts. For many people this may be yesterday's news, but I am posting it here as a reminder to myself and in hope that it might help someone else.
Windows command shell (sometimes erroneously called DOS prompt) provides %DATE%
and %TIME%
environment variables which, unsurprisingly, return current date and time. On the other hand, it is possible to extract a group of characters from any environment variable using following syntax:
%VARIABLE:~START,LENGTH%
where VARIABLE
is the name of the environment variable, START
is the zero-based index of the first character to be retrieved and LENGTH
is the length of the string to be retrieved. E.g. %USERNAME:~1,3%
would return second, third and fourth letter of the current user's name.
So in order to create a time stamp, we define a temporary environment variable with value defined by parts of %DATE%
and %TIME%
. Then we use this variable to create file names. Please note that the exact indices will depend on your time format settings. In a batch file or a script it would look like this:
set backup_time=%date:~10,4%_%date:~7,2%_%date:~4,2%
set backup_detailed=%backup_time%__%time:~0,2%_%time:~3,2%_%time:~6,2%
md d:\zzz_%backup_time%
md d:\zzz_%backup_detailed%
Output of the batch file is:
D:\tmp>set backup_time=2008_09_23
D:\tmp>set backup_detailed=2008_09_23__15_50_31
D:\tmp>md d:\zzz_2008_09_23
D:\tmp>md d:\zzz_2008_09_23__15_50_31