How does variable expansion of multiple instances of the same variable in a Batch File command work?

I know that without delayed expansion the contents of a variable are substituted for that variable at the time the command that references it is parsed.

My question is, what happens if a command references a variable multiple times?

Say a command references the %date% variable three times, will the parsing mechanism retrieve the date three separate times, or just once, (and then plugs it in wherever it appears in the line?

This musing began because I use the line

set var=%date:~6%-%date:~3,2%-%date:~0,2%

to obtain the date in my preferred format. (Basically it takes the date in the original dd/mm/yyyy form and reorganises it to yyyy-mm-dd)

But then the hypothetical possibility occurred to me: what if I invoke this command 1 millisecond before midnight on the 31st March 2022? If the parsing mechanism retrieves the date fresh each time it comes across it, isn't it theoretically possible that midnight might come during the parsing? And so rather than getting an outputt of either "2022-03-31" or "2022-04-01", I might instead get "2022-03-01"?


Solution 1:

Actually I have found the answer. The parsing mechanism DOES keep rereferincing the variable.

Oh well, I was hoping that the variable would be retrieved just once, and then substituted in wherever it appears in the command block.

I demonstrated this with the following code.

    @echo off
    if exist C:\ (
    set var1=%time%
    echo %time%
    echo %time%
    [...]
    echo %time%
    echo %time%
    set var2=%time%
    )
    echo start %var1%
    echo end %var2%
    timeout /nobreak -1

(I have left out about a thousand "echo %time%" lines in the middle)

The start and end times show a .01 difference.

Looks like I'm going to change my date format converter to:

    set frozen_date=%date%
    set var=%frozen_date:~6%-%frozen_date:~3,2%-%frozen_date:~0,2%