Search code examples
windowsbatch-file

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


I have this part of script that create a variable called fileName used later to name a file.

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

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


Solution

  • Opening 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 dynamic variable references.

    The format of the date and the time depends on Windows region and language settings. It is necessary for that reason 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?

    In output help of command SET is explained also %Variable:~X,Y% to get a substring of a string of a variable value 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
    

    The above command line defines an environment variable with name fileName

    • starting with fixed string db_,
    • appending with %date:~-4,4% the last four 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 two characters of the current locale time which is obviously the hour with always two digits in 24-hour format,
    • 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 at the beginning of the date string.