Walker News

How To Create File Name Using Date Or Time Value In Windows Batch File?

Question: At the Windows Command Prompt (better known as DOS prompt by veterans), what is the DOS command syntax for generating file name based on timestamp value?

Lately, I was asked to create a simple solution for archiving a system log file on daily basis (while waiting for application developer to build this feature into the program).

So, I created a really simple Windows batch file, containing only one line, that uses date value to generate file name (the CD line is not necessary, if you know the “trick”):
cd C:\apps
move elog elog.%date:~-4,4%%date:~-8,3%%date:~-11,2%

which effectively move elog to become elog.YYYYmmmDD, according to the date format used by that Windows system:

Use dos command to create file name based on date-time value.

So, the Windows date command syntax to print “Jan” is as follow:
echo %date:~-8,3%

where -8 means to extract 8 characters from the right end (i.e. Jan-2013) and then return 3 characters from the left end of this extracted string to echo command (thus the printed result is Jan).
Apparently, if your Windows system is using US date format (a different format), then you’ve to make changes to the date syntax accordingly.

Besides date, similar syntax is also applicable to the Windows time command:
C:\>time
The current time is: 17:38:11.16
Enter the new time:

C:\>echo %time:~-11,2%%time:~-8,2%%time:~-5,2%
173811

If the Windows Batch file is automated to run multiple times within a day, or via endless for loop, then combining both date and time command output can perfectly create unique file names in a folder.

Custom Search

2014  •  Privacy Policy