How to make a batch file rename a file to the date or time

Updated: 01/24/2018 by Computer Hope
Batch file

There are a few different methods of how this can be done. The example below shows how you can use the date command in the for command to extract the current date and use that data to rename the file. Each of the for commands listed in this page would be placed into a batch file.

Date

for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "hope.txt" %%e-%%f-%%g.txt

Below is a breakdown of the above command and what it all means.

  • for /f - The for command and the /f switch.
  • "tokens=1-5 delims=/ " - How many tokens the incoming data (the date) will be broken into; 1-5 is five different tokens. Delims is short for delimiters and break up the date in this example, the / (forward slash) and a space (space before the quote).
  • %%d - The beginning character used for the token. Since there are 5 tokens in this example it would be d,e,f,g, and h.
  • in ("%date%") - The data, which is the %date% (date) of the computer.
  • do - What the for command does. The rename command can be substituted for anything else.
  • rename "hope.txt" %%e-%%f-%%g.txt - Rename the file "hope.txt" to the tokens e,f, and g with a .txt file extension. This example also has a - (hyphen) in-between each token to separate the month, day, and year in the file name.

When %date% is used in a batch file, it displays the date in the following format: Sun 09/02/2007. This command breaks this date into the tokens: "Sun" (%%d), "09" (%%e), "02" (%%f), and "2007" (%%g).

In this example, using the above date mentioned hope.txt would be renamed to 09-02-2007.txt.

Time

for /f "tokens=1-5 delims=:" %%d in ("%time%") do rename "hope.txt" %%d-%%e.txt

This command is similar to the above example. However, instead of using the forward slash and space to break up the data, we're using a : (colon) because the time uses this character. Finally, because we're renaming the file to only the hour and minute this example is only using the d and e token. Additional information about what everything in this line means is found in the above date example.

When %time% is used in a batch file, it displays the following format: 19:34:52.25. This command breaks this time into the tokens: "19" (%%d), "34" (%%e), and "52.25" (%%f).

In this example, using the above time mentioned hope.txt would be renamed to 19-34.txt.