What does %date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2% mean?

Opening in a command prompt window and running there set /? outputs the help for command SET.

There is explained on last help page that %DATE% expands to the current locale date and %TIME% to the current locale time on parsing the line containing those environment variable references.

The format of the date and the time depends on Windows region and language settings. Therefore it is necessary to execute in a command prompt window

echo Date is: %DATE%
echo Time is: %TIME%

or alternatively

echo %DATE% %TIME%

best executed before 10:00 AM to know the locale date and time string formats. Is the date with weekday? What is the order of day, month and year in date string? Is the time in 12 or 24 hours format? Is the time always with a two digit hour?

And in output help of command SET there is explained also %Variable:~X,Y% to get a substring of a string of an environment variable from position X in string with Y characters length.

The first character in a string has position number (character index) 0.
A negative value for X means X characters from end of string (from right side).

set fileName=db_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%.bak

defines a variable with name fileName

  • starting with fixed string db_,
  • appending with %date:~-4,4% the last 4 characters of the current locale date which is obviously the year,
  • appending with %date:~-10,2% the tenth and ninth characters from right side of the current locale date which is most likely the month,
  • appending with %date:~-7,2% the seventh and sixth characters from right side of the current locale date which is most likely the day,
  • appending an underscore as separator between date in format YYYYMMDD and time in format HHmm,
  • appending with %time:~0,2% the first 2 characters of the current locale time which is obviously the hour,
  • appending with %time:~3,2% the fourth and fifth character of the current locale time which is obviously the minute and
  • appending the file extension .bak.

The result of this variable definition with several substrings can be verified by executing in a command prompt window:

echo db_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%.bak

The substring references from date string are done from right side (end of string) instead of left side (beginning of string) to make the definition independent on weekday present or missing on beginning of date string.

Leave a Comment