I'm looking to timestamp every echo
with hh:mm:ss
in batch. I have been using %time:~0,-3%
and it worked great until I had to use set /p
. It omitted the leading space of single digit hours making the line misaligned compared to the rest.
Example:
@echo off
echo %time:~0,-3% Hello world!
echo %time:~0,-3% It's a sunny day outside.
set /p "state=%time:~0,-3% How are you? "
echo %time:~0,-3% That's great!
pause >nul
Output:
1:59:55 Hello world!
1:59:55 It's a sunny day outside.
1:59:55 How are you?
2:00:02 That's great!
I could use set ctime=%time:~0,3%%time:~3,3%%time:~6,2%
and echo %ctime: =0%
after but that would result in many redundant lines.
Is there a way to combine %time:~0,-3%
and %time: =0%
? That would sort me out.
Or maybe force set /p
not to omit space character? That would work too.
You can use a little trickery by capturing a backspace to a variable.
@echo off
:: Define BS to contain a backspace
for /f %%a in ('"prompt $H&for %%b in (1) do rem"') do set "BS=%%a"
echo %time:~0,-3% Hello world!
echo %time:~0,-3% It's a sunny day outside.
set /p "state=_%BS%%time:~0,-3% How are you? "
echo %time:~0,-3% That's great!
pause