Name a file with timestamp in DOS

Sometimes while scripting in DOS on a system running Windows operating system, you need to name files with a unique timestamp. A typical use case would be for a systems administrator trying to manage logs by hand for a custom desktop application or on a server.

Combining a few commands offered in the DOS shell, you can make this happen.

For example:

for /f "tokens=1-3 delims=/:/./ " %%a in ("%time%") do (set mytime=%%a%%b%%c)
for /f "tokens=1-4 delims=// " %%a in ("%date%") do (set mydate=%%d%%c%%b)
echo %mydate%_%mytime%





The very versatile for command iterates over all the tokens provided by system variables %DATE% and %TIME%. Once you have the tokens in hand, you can assign them to a variable that you define (mytime, mydate). The key thing to keep in mind is the delimiters that you use to parse the fields off of the environment variables. To parse the date we can use forward slash and a space. To parse time we can use a colon, a period and a space.

I thought I’d post this on the internet after I kept running into countless forums and websites like stackoverflow without a simple explanation.

For those not familiar with DOS environment, sometimes a simpler explanation like this means a lot.