Getting the Current Timestamp in a Batch File

While fiddling around with different backup tools I finally settled with robocopy and a simple batch file. Being the control freak I am, I looked for a way to have single log files for each backup run in the format YYYYMMDDHHMMSS_description.log. Luckily there’s a way to acomplish this with some batch magic only.

You can get the current date and time in your locale with the environment variables %date% and %time%. Try entering the following command on the command line:

echo %date% %time%

As already said, the strings are localized, so the following examples will only work with a german locale set, but the technique will do in any language of course ;-)

Now, that we have the current date and time, we can extract the required parts with simple substring operations … Yes, that’s right, you can do substrings in a batch file! For an overview of even more cool features check out the set help on the command line as follows:

set /?

All you have to do is to suffix the variable with a colon and a tilde and add the start position as well as the length separated with a comma. To get the day part of a german date you would do:

echo %date:~0,2%

Now on to the promised timestamp. We simply have to set a new variable to the concatenated substrings in the right order:

set currentTimestamp=%date:~6,4%%date:~3,2%%date:~0,2%%time:~0,2%%time:~3,2%%time:~6,2%
echo %currentTimestamp%

We can then insert the timestamp in our filename and the filename in the executed command:

set logFileName=%timestamp%_description.log
robocopy.exe ... /LOG+:%logFileName%

Oh, and it might be a good idea to clean up your variables:

set currentTimestamp=
set logFileName=%timestamp%_description.log

That’s it for today. I hope you learned something useful and I’m looking forward to read you again soon.

If you’ve got any ideas or annotations for this post or simply want to insult me, don’t hesitate to leave a comment. It won’t hurt ;-)

Cheers
Sascha

A happy new year

A happy, exciting and successful new year 2009 to all of you!