Although it is possible to do it in one line (delayed expansion needed), I don't think, it serves readability:
@echo off
setlocal enabledelayedexpansion
set "var=%time:~0,8%" & set "var=!var::=_!"
echo %var%
I suggest moving the formatting to a subroutine. (Not exactly a one-liner, but keeps your main code clean and readable).
@echo off
call :FormatTime var="%time%"
echo %var%
goto :eof
:FormatTime
set "_=%~2"
set "_=%_:~0,8%" :: get 'HH:MM:SS'
set "_=%_: =0%" :: replace ' ' with '0'
set "%1=%_::=_%" :: replace ':' with '_'
goto :eof
The call
defines the variable name for the result (var
here) and the string to format (%time%
here). Usually, the two arguments are separated by a space, but as =
also acts as a standard delimiter, we can use that to make the line even more readable (intuitive).
Enclosing the string in quotes ("%time%
) enables us to catch the space (" 8:12:00,99"
) to be able to replace it with a zero.
I also used another method to strip the milliseconds part (language independent).