How do I print the time (in ms) in a Windows batch file?
I want to measure the time that passes between lines in my batch file, but Windows\'s \"time /T\" does not p
You have to be careful with what you want to do, because it is not just about to get the time.
The batch has internal variables to represent the date and the tme: %DATE% %TIME%. But they dependent on the Windows Locale.
%Date%:
%TIME%:
Now, how long your script will work and when? For example, if it will be longer than a day and does pass the midnight it will definitely goes wrong, because difference between 2 timestamps between a midnight is a negative value! You need the date to find out correct distance between days, but how you do that if the date format is not a constant? Things with %DATE% and %TIME% might goes worser and worser if you continue to use them for the math purposes.
The reason is the %DATE% and %TIME% are exist is only to show a date and a time to user in the output, not to use them for calculations. So if you want to make correct distance between some time values or generate some unique value dependent on date and time then you have to use something different and accurate than %DATE% and %TIME%.
I am using the wmic windows builtin utility to request such things (put it in a script file):
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE`) do if "%%i" == "LocalDateTime" echo.%%j
or type it in the cmd.exe console:
for /F "usebackq tokens=1,2 delims==" %i in (`wmic os get LocalDateTime /VALUE`) do @if "%i" == "LocalDateTime" echo.%j
The disadvantage of this is a slow performance in case of frequent calls. On mine machine it is about 12 calls per second.
If you want to continue use this then you can write something like this (get_datetime.bat):
@echo off
rem Description:
rem Independent to Windows locale date/time request.
rem Drop last error level
cd .
rem drop return value
set "RETURN_VALUE="
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if "%%i" == "LocalDateTime" set "RETURN_VALUE=%%j"
if not "%RETURN_VALUE%" == "" (
set "RETURN_VALUE=%RETURN_VALUE:~0,18%"
exit /b 0
)
exit /b 1
Now, you can parse %RETURN_VALUE% somethere in your script:
call get_datetime.bat
set "FILE_SUFFIX=%RETURN_VALUE:.=_%"
set "FILE_SUFFIX=%FILE_SUFFIX:~8,2%_%FILE_SUFFIX:~10,2%_%FILE_SUFFIX:~12,6%"
echo.%FILE_SUFFIX%