Vous êtes sur la page 1sur 18

1/29/2019 Calculate time difference in Windows batch file - Stack Overflow

Make your voice heard. Take the 2019 Developer Survey now

Calculate time difference in Windows batch file Ask Question

How can I get the difference between


two times in a Batch file? Because I
33 want to print it in an HTML file.

I thought this would be possible, but it


isn't.

Set "tijd=%time%"
17 echo %tijd%
echo %time%-%tijd%

Results:

11:07:48,85
11:16:58,99-11:07:48,85

But what I want is:

00:09:10,14

Or 9 minutes and 10 seconds or 550


seconds

windows batch-file time

edited Apr 16 '17 at 6:13


gregv21v
31 1 7

asked Mar 29 '12 at 9:21


Gynnad
1,272 3 30 49

3 While it is possible (just search for


date/time math in batch, honestly)
you shouldn't do so. And I probably
shouldn't even ask why a batch file is
involved in serving HTML content, I
guess. – Joey Mar 29 '12 at 9:23

1 Why I shouldn't do so? I do serving


HTML because I deploy some plugins
and the only way to look if the were
succesful is to search through the
By using our site, you acknowledge
logfile that'succesful'..
on the word you have read
Andand understand our Cookie Policy, Privacy Policy, and our
Terms of Service. ofcourse I want feedback because it
are more then 100 plugins. So I can
https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 1/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
see witch were succesful and witch
failed. Have you any better method? –
Gynnad Mar 29 '12 at 9:26

2 Why use PowerShell if it is also


Possible in a batch file? I can use a
batchfile in Windows 7, Vista, XP
without installing anything. Powershell
is only 'standard' on Windows 7. On
the other OS's I need to install it.. It
will cost more time, while it is
possible in a batch file.. – Gynnad
Mar 29 '12 at 9:32

4 I agree with Joey, don't write


production processes in batch (and
I'm a batch fanatic!), it has to much
limitations and it's hard to implement
complex tasks. I would choose
phython/perl or some real language
that will work independent of MS (that
ensures it will still work in three years)
and you can switch even to linux – jeb
Mar 29 '12 at 9:48

1 I'm using it for testing of the builds


where correct. Afterwards I will delete
them. It is only a test if they deploy.
When they are I will put a Succesful in
the HTML file, when it fails I will put a
Failed in the HTML file. Then I will
delete the plugin. And so for all the
plugins. It is not for production or
something, it is only to see if it works.
And I have now a batch file and it
works very nice. So I don't understand
why I should go to Powershell or
anything other? – Gynnad Mar 29
'12 at 10:04

8 Answers

@echo off

rem Get start time:


50 for /F "tokens=1-4 delims=:.," %%a i
set /A "start=(((%%a*60)+1%%b %%
)

rem Any process here...

rem Get end time:


for /F "tokens=1-4 delims=:.," %%a i
set /A "end=(((%%a*60)+1%%b %% 10
)

rem Get elapsed time:


set /A elapsed=end-start

rem Show elapsed time:


set /A hh=elapsed/(60*60*100), rest=
rest%%=60*100, ss=rest/100, cc=rest%
if %mm% lss 10 set mm=0%mm%
if %ss% lss 10 set ss=0%ss%
By using our site,ifyou acknowledge that you have read and understand our
%cc% lss 10 set cc=0%cc%
, , and our
. echo %hh%:%mm%:%ss%,%cc%

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 2/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow

EDIT 2017-05-09: Shorter method


added

I developed a shorter method to get the


same result, so I couldn't resist to post
it here. The two for commands used
to separate time parts and the three
if commands used to insert leading
zeros in the result are replaced by two
long arithmetic expressions, that could
even be combined into a single longer
line.

The method consists in directly


convert a variable with a time in
"HH:MM:SS.CC" format into the
formula needed to convert the time to
centiseconds, accordingly to the
mapping scheme given below:

HH : MM :

(((10 HH %%100)*60+1 MM %%100)*6

That is, insert (((10 at beginning,


replace the colons by %%100)*60+1 ,
replace the point by %%100)*100+1 and
insert %%100 at end; finally, evaluate
the resulting string as an arithmetic
expression. In the time variable there
are two different substrings that needs
to be replaced, so the conversion must
be completed in two lines. To get an
elapsed time, use (endTime)-
(startTime) expression and replace
both time strings in the same line.

EDIT 2017/06/14: Locale independent


adjustment added

@echo off
setlocal EnableDelayedExpansion

set "startTime=%time: =0%"

set /P "=Any process here..."

set "endTime=%time: =0%"

rem Get elapsed time:


set "end=!endTime:%time:~8,1%=%%100)
"start=!startTime:%time:~8,1%=%%100)
set /A "elap=((((10!end:%time:~2,1%=
((((10!start:%time:~2,1%=%%100)*60+1

rem Convert elapsed time to HH:MM:SS


set /A
"cc=elap%%100+100,elap/=100,ss=elap%
By using our site, you acknowledge that you have read and understand our , , and our
. echo Start: %startTime%

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 3/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
echo End: %endTime%
echo Elapsed: %hh:~1%%time:~2,1%%mm

You may review a detailed explanation


of this method at this answer.

edited Jun 14 '17 at 18:59

answered Mar 30 '12 at 0:34


Aacini
51.3k 7 52 74

Well done, I like this one a lot. I would


only say that most likely people are
setting the start time earlier in the
script so I would set the variable in
start / finish values instead of actually
getting it and formatting it at the time
it was recorded. I am going to post a
re-hash of yours below. – Mike Q Jun
20 '13 at 14:53

This worked for me -- it does make


locale specific assumptions -- that ","
is used a decimal separator in the
output (should be easy enough to
detect this since you're parsing
%time% anyway...), but with that one

character of code change, it works for


me, and looks right (in my locale). –
BrainSlugs83 Sep 16 '14 at 19:25

And for the updated answer you have


to replace [...]Time:. with
[...]Time:, if you have ',' as
decimal separator (locales are
horrible). – Arsenal Jun 13 '17 at 12:20

@Arsenal: yes, but the locale


independent adjustment is very
simple. See my second edit... –
Aacini Jun 14 '17 at 18:52

Thanks for that. For a reason out of


my understanding the locale
dependent solution stopped working
today. So the update is highly
appreciated. – Arsenal Jun 19 '17 at
6:46

As answered here: How can I use a


Windows batch file to measure the
39 performance of console application?

Below batch "program" should do


what you want. Please note that it
By using our site,outputs the data in
you acknowledge centiseconds
that you have read and understand our , , and our
instead of milliseconds. The precision
.

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 4/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
of the used commands is only
centiseconds.

Here is an example output:

STARTTIME: 13:42:52,25
ENDTIME: 13:42:56,51
STARTTIME: 4937225 centiseconds
ENDTIME: 4937651 centiseconds
DURATION: 426 in centiseconds
00:00:04,26

Here is the batch script:

@echo off
setlocal

rem The format of %TIME% is HH:MM:S


set STARTTIME=%TIME%

rem here begins the command you wan


dir /s > nul
rem here ends the command you want

set ENDTIME=%TIME%

rem output as time


echo STARTTIME: %STARTTIME%
echo ENDTIME: %ENDTIME%

rem convert STARTTIME and ENDTIME t


set /A STARTTIME=(1%STARTTIME:~0,2%
(1%STARTTIME:~6,2%-100)*100 + (1%ST
set /A ENDTIME=(1%ENDTIME:~0,2%-100
(1%ENDTIME:~6,2%-100)*100 + (1%ENDT

rem calculating the duratyion is ea


set /A DURATION=%ENDTIME%-%STARTTIM

rem we might have measured the time


if %ENDTIME% LSS %STARTTIME% set se

rem now break the centiseconds down


centiseconds
set /A DURATIONH=%DURATION% / 36000
set /A DURATIONM=(%DURATION% - %DUR
set /A DURATIONS=(%DURATION% - %DUR
set /A DURATIONHS=(%DURATION% - %DU
%DURATIONS%*100)

rem some formatting


if %DURATIONH% LSS 10 set DURATIONH
if %DURATIONM% LSS 10 set DURATIONM
if %DURATIONS% LSS 10 set DURATIONS
if %DURATIONHS% LSS 10 set DURATION

rem outputing
echo STARTTIME: %STARTTIME% centise
echo ENDTIME: %ENDTIME% centisecond
echo DURATION: %DURATION% in centis
echo %DURATIONH%:%DURATIONM%:%DURAT

endlocal
goto :EOF

edited May 23 '17 at 10:31


Community ♦
By using our site, you acknowledge
1 that
1 you have read and understand our , , and our
.
answered Mar 30 '12 at 7:05

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 5/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
Gynnad
1,272 3 30 49

2 Aacini's below I think is better


because it's more straight forward.
Also your script spits out errors on
my system and doesn't always
perform the math operations. At
times, I'm not sure what the issue
was but it's not doing it now.. –
Mike Q Jun 20 '13 at 14:49

4 Not bad, but still a major bug left, as


Mike stated already. There are (at
least :-) two special behaviours an
algorithm has to work around: 1. The
first is that Batches think that
numbers prefixed by zero are octal
numbers. This is adressed here
correctly by prefixing with a "1" and
subtract 100 again. 2. But the other
issue is that hours consist
sometimes of one Digit ("2:") and
sometimes of two ("12:"). Maybe this
is locale specific, but I think, it is not.
So the ":~02,2%" is failing here.
Nevertheless, this does not work
always, the solution from Aacini
seems to work better. – Philm Mar 5
'14 at 11:16

Seems to be make assumptions


based on specific locale... –
BrainSlugs83 Sep 16 '14 at 19:24

Of course, regional settings apply


here so you better know how any
other user that might run this script is
set up... Me, for example: when it's
01:35 AM, my "hours" become: "1:"
(rather than "01", which would be fine)
and that will fail the above script.
Better add some logic to cover that! –
DraxDomax Nov 17 '15 at 14:12

Line 25: if %ENDTIME% LSS


%STARTTIME% set set /A
DURATION=%STARTTIME%-%ENDTIME%
- I don't get it how it's suppose to
work!? Think it should be if
%ENDTIME% LSS %STARTTIME% set
set /A
DURATION=%DURATION%+8640000 .
Constant 8640000 is a number of
centiseconds in one day. – MKPS
Apr 16 '16 at 0:11

A re-hash of Aacini's code because


most likely you are going to set the
20 start time as a variable and want to
save that data for output:
By using our site, you acknowledge that you have read and understand our , , and our
. @echo off

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 6/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
rem ****************** MAIN COD
set STARTTIME=%TIME%

rem Your code goes here (remove


ping -n 4 -w 1 127.0.0.1 >NUL

set ENDTIME=%TIME%

rem ****************** END MAIN

rem Change formatting for the st


for /F "tokens=1-4 delims=:.," %
set /A "start=(((%%a*60)+1%%b
)

for /F "tokens=1-4 delims=:.," %


set /A "end=(((%%a*60)+1%%b %
)

rem Calculate the elapsed time b


set /A elapsed=end-start

rem Format the results for outpu


set /A hh=elapsed/(60*60*100), r
rest%%=60*100, ss=rest/100, cc=rest%
if %hh% lss 10 set hh=0%hh%
if %mm% lss 10 set mm=0%mm%
if %ss% lss 10 set ss=0%ss%
if %cc% lss 10 set cc=0%cc%

set DURATION=%hh%:%mm%:%ss%,%cc%

echo Start : %STARTTIME%


echo Finish : %ENDTIME%
echo ---------------
echo Duration : %DURATION%

Output:

Start : 11:02:45.92
Finish : 11:02:48.98
---------------
Duration : 00:00:03,06

edited Jun 20 '13 at 16:28

answered Jun 20 '13 at 15:03


Mike Q
2,598 1 25 37

... you guys know batch files have


GOSUB-like behavior, right? (via the
CALL statement -- you can CALL a
label, pass it parameters and it can
pass back return values... you can
google the syntax but it's not too
hard). – BrainSlugs83 Sep 16 '14 at
19:26

Yes, when I used this in my script I


called it like a function. – Mike Q Sep
18 '14 at 18:39

By using our site, you


Toacknowledge that you
account for ending have
after read and
midnight, I understand our , , and our
. would alter the second for loop to:
for /F "tokens=1-4 delims=:.,"
%% i ("% %") d ( if
https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 7/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
%%a in ("%ENDTIME%") do ( if
%ENDTIME% GTR %STARTTIME% set
/A "end=(((%%a*60)+1%%b %%
100)*60+1%%c %% 100)*100+1%%d
%% 100" if %ENDTIME% LSS
%STARTTIME% set /A "end=
((((%%a+24)*60)+1%%b %%
100)*60+1%%c %% 100)*100+1%%d
%% 100" ) – David Jan 7 at 19:50

good call David – Mike Q Jan 7 at


20:06

Based on previous answers, here are


reusable "procedures" and a usage
2 example for calculating the elapsed
time:

@echo off
setlocal

set starttime=%TIME%
echo Start Time: %starttime%

REM --------------------------------
REM --- PUT THE CODE YOU WANT TO MEA
REM --------------------------------

set endtime=%TIME%
echo End Time: %endtime%
call :elapsed_time %starttime% %endt
echo Duration: %duration%

endlocal
echo on & goto :eof

REM --- HELPER PROCEDURES ---

:time_to_centiseconds
:: %~1 - time
:: %~2 - centiseconds output variabl
setlocal
set _time=%~1
for /F "tokens=1-4 delims=:.," %%a i
set /A "_result=(((%%a*60)+1%%b %
)
endlocal & set %~2=%_result%
goto :eof

:centiseconds_to_time
:: %~1 - centiseconds
:: %~2 - time output variable
setlocal
set _centiseconds=%~1
rem now break the centiseconds down
centiseconds
set /A _h=%_centiseconds% / 360000
set /A _m=(%_centiseconds% - %_h%*36
set /A _s=(%_centiseconds% - %_h%*36
set /A _hs=(%_centiseconds% - %_h%*3
rem some formatting
if %_h% LSS 10 set _h=0%_h%
if %_m% LSS 10 set _m=0%_m%
if %_s% LSS 10 set _s=0%_s%
By using our site,if %_hs%
you LSS 10 that
acknowledge set you
_hs=0%_hs%
have read and understand our , , and our
set _result=%_h%:%_m%:%_s%.%_hs%
. endlocal & set %~2=%_result%

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 8/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
goto :eof

:elapsed_time
:: %~1 - time1 - start time
:: %~2 - time2 - end time
:: %~3 - elapsed time output
setlocal
set _time1=%~1
set _time2=%~2
call :time_to_centiseconds %_time1%
call :time_to_centiseconds %_time2%
set /A _duration=%_centi2%-%_centi1%
call :centiseconds_to_time %_duratio
endlocal & set %~3=%_result%
goto :eof

answered Oct 7 '14 at 7:02


yinon
699 5 8

Just in case centiseconds is


negative, :centiseconds_to_time
can check and prepend a minus sign.
set "_n=" followed by if
%_centiseconds% lss 0 set "_n=-
" & set /A _centiseconds*=-1
then at the end: set
_result=%_n%%_h%:%_m%:%_s%.%_hs
% so that call
:centiseconds_to_time -3000
test_neg gives test_neg =
-00:00:30.00 – Jesse Chisholm
Jun 28 '18 at 17:10

Not needed in this example script, as


duration is always non-negative. –
Jesse Chisholm Jun 28 '18 at 17:11

Fixed Gynnad's leading 0 Issue. I


fixed it with the two Lines
2
SET STARTTIME=%STARTTIME: =0%
SET ENDTIME=%ENDTIME: =0%

Full Script ( CalculateTime.cmd ):

@ECHO OFF

:: F U N C T I O N S

:__START_TIME_MEASURE
SET STARTTIME=%TIME%
SET STARTTIME=%STARTTIME: =0%
EXIT /B 0

:__STOP_TIME_MEASURE
SET ENDTIME=%TIME%
SET ENDTIME=%ENDTIME: =0%
SET /A STARTTIME=(1%STARTTIME:~0,2%-
(1%STARTTIME:~6,2%-100)*100 + (1%STA
SET /A ENDTIME=(1%ENDTIME:~0,2%-100)
By using our site,(1%ENDTIME:~6,2%-100)*100
you acknowledge that you have+ read and understand our
(1%ENDTI , , and our
. SET /A DURATION=%ENDTIME%-%STARTTIME
IF %DURATION% == 0 SET TIMEDIFF=00:0

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 9/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
IF %ENDTIME% LSS %STARTTIME% SET /A
SET /A DURATIONH=%DURATION% / 360000
SET /A DURATIONM=(%DURATION% - %DURA
SET /A DURATIONS=(%DURATION% - %DURA
SET /A DURATIONHS=(%DURATION% - %DUR
%DURATIONS%*100)
IF %DURATIONH% LSS 10 SET DURATIONH=
IF %DURATIONM% LSS 10 SET DURATIONM=
IF %DURATIONS% LSS 10 SET DURATIONS=
IF %DURATIONHS% LSS 10 SET DURATIONH
SET TIMEDIFF=%DURATIONH%:%DURATIONM%
EXIT /B 0

:: U S A G E

:: Start Measuring
CALL :__START_TIME_MEASURE

:: Print Message on Screen without L


ECHO|SET /P=Execute Job...

:: Some Time pending Jobs here


:: '> NUL 2>&1' Dont show any Messag
MyJob.exe > NUL 2>&1

:: Stop Measuring
CALL :__STOP_TIME_MEASURE

:: Finish the Message 'Execute Job.


ECHO [Done] (%TIMEDIFF%)

:: Possible Result
:: Execute Job... [Done] (00:02:12,3
:: Between 'Execute Job... ' and '[D

edited Jun 25 '16 at 10:36

answered Jun 25 '16 at 6:26


Dirk Schiller
178 2 11

Here is my attempt to measure time


difference in batch.
2
It respects the regional format of
%TIME% without taking any
assumptions on type of characters for
time and decimal separators.

The code is commented but I will also


describe it here.

It is flexible so it can also be used to


normalize non-standard time values as
well

The main function :timediff

:: timediff
By using our site,::
you acknowledge
Input that you
and output have is
format read andsaunderstand our
the , , and our
. :: If EndTime is less than StartTime
:: EndTime will be treated as a ti

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 10/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
:: in that case, function measures
24 hours minus 1 centisecond
:: time elements can have values g
12:247:853.5214
:: provided than the total represe
:: otherwise the result will not b
:: If EndTime is greater than or equ
:: No formal limitation applies to
:: except that total represented t

:timediff <outDiff> <inStartTime> <i


(
setlocal EnableDelayedExpansion
set "Input=!%~2! !%~3!"
for /F "tokens=1,3 delims=012345
"time.delims=%%A%%B "
)
for /F "tokens=1-8 delims=%time.deli
for %%A in ("@h1=%%a" "@m1=%%b"
"@s2=%%g" "@c2=%%h") do (
for /F "tokens=1,2 delims=="
for /F "tokens=* delims=
)
)
set /a "@d=(@h2-@h1)*360000+(@m2
(@d>>31)&1, @d+=(@sign*24*360000), @
@d%%=6000, @s=@d/100, @c=@d%%100"
)
(
if %@h% LEQ 9 set "@h=0%@h%"
if %@m% LEQ 9 set "@m=0%@m%"
if %@s% LEQ 9 set "@s=0%@s%"
if %@c% LEQ 9 set "@c=0%@c%"
)
(
endlocal
set "%~1=%@h%%time.delims:~0,1%%
exit /b
)

Example:

@echo off
setlocal EnableExtensions
set "TIME="

set "Start=%TIME%"
REM Do some stuff here...
set "End=%TIME%"

call :timediff Elapsed Start End


echo Elapsed Time: %Elapsed%

pause
exit /b

:: put the :timediff function here

Explanation of the :timediff


function:

function prototype :timediff <outDi

Input and output format is the same


format as %TIME%

It takes
By using our site, 3 parameters
you acknowledge that from left read
you have to right:
and understand our , , and our
.

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 11/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
Param1: Name of the environment
variable to save the result to.
Param2: Name of the environment
variable to be passed to the function
containing StartTime string
Param3: Name of the environment
variable to be passed to the function
containing EndTime string

If EndTime is less than StartTime


then:

EndTime will be treated as a time


in the next day
in that case, the function
measures time difference
between a maximum distance of
24 hours minus 1 centisecond
time elements can have values
greater than their standard
maximum value ex:
12:247:853.5214
provided than the total
represented time does not exceed
24*360000 centiseconds or
(24:00:00.00) otherwise the result
will not be meaningful.

If EndTime is greater than or


equals to StartTime then:
No formal limitation applies to the
value of elements,
except that total represented time
can not exceed 2147483647
centiseconds.

More examples with literal and non-


standard time values

Literal example with EndTime


less than StartTime:

@echo off
setlocal EnableExtensions

set "start=23:57:33,12"
set "end=00:02:19,41"

call :timediff dif start end

echo Start Time: %start%


echo End Time: %end%
echo,
echo Difference: %dif%
echo,

pause
exit /b
By using our site, you acknowledge that you have read and understand our , , and our
:: put the :timediff function here
.

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 12/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
Output:

Start Time: 23:57:33,12


End Time: 00:02:19,41

Difference: 00:04:46,29

Normalize non-standard time:

@echo off
setlocal EnableExtensions

set "start=00:00:00.00"
set "end=27:2457:433.85935"

call :timediff normalized start end

echo,
echo %end% is equivalent to %normali
echo,

pause
exit /b

:: put the :timediff function here

Output:

27:2457:433.85935 is equivalent to 6

Last bonus example:

@echo off
setlocal EnableExtensions

set "start=00:00:00.00"
set "end=00:00:00.2147483647"

call :timediff normalized start end

echo,
echo 2147483647 centiseconds equals
echo,

pause
exit /b

:: put the :timediff function here

Output:

2147483647 centiseconds equals to 59

edited Dec 19 '18 at 15:33

answered May 7 '18 at 6:21


sst
782 1 5 10
By using our site, you acknowledge that you have read and understand our , , and our
.

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 13/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow

Using a single function with the


possibility of custom unit of measure
1 or formatted. Each time the function is
called without parameters we restarted
the initial time.

@ECHO OFF

ECHO.
ECHO DEMO timer function
ECHO --------------------

SET DELAY=4

:: First we call the function withou


CALL:timer

:: We put some code we want to measu


ECHO.
ECHO Making some delay, please wait
ECHO.

ping -n %DELAY% -w 1 127.0.0.1 >NUL

:: Now we call the function again wi

CALL:timer elapsed_time

ECHO by Default : %elapsed_time%

CALL:timer elapsed_time "s"

ECHO in Seconds : %elapsed_time%

CALL:timer elapsed_time "anything"

ECHO Formatted : %elapsed_time% (H

ECHO.
PAUSE

:: Elapsed Time Function


:: ---------------------------------
:: The returned value is in centisec
:: to be in another unit of measure
::
:: Parameters:
:: <return> the retu
:: [formatted] s (for s
:: anything
:: ---------------------------------
:timer <return> [formatted]
SetLocal EnableExtensions Enable

SET _t=%time%
SET _t=%_t::0=: %
SET _t=%_t:,0=, %
SET _t=%_t:.0=. %
SET _t=%_t:~0,2% * 360000 + %_t
SET /A _t=%_t%

:: If we call the function witho


SET _r=%~1
IF NOT DEFINED _r (
EndLocal & SET TIMER_START_T
)

By using our site, youSET /A _t=%_t%


acknowledge that -you
%TIMER_START_TI
have read and understand our , , and our
. :: In the case of wanting a form

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 14/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
SET _f=%~2
IF DEFINED _f (

IF "%_f%" == "s" (

SET /A "_t=%_t% / 100"

) ELSE (
IF "%_f%" == "m" (

SET /A "_t=%_t% / 60

) ELSE (

IF "%_f%" == "h" (

SET /A "_t=%_t%

) ELSE (

SET /A "_h=%_t%
SET /A "_m=(%_t%
SET /A "_s=(%_t%
SET /A "_cs=(%_t

IF !_h! LSS 10 S
IF !_m! LSS 10 S
IF !_s! LSS 10 S
IF !_cs! LSS 10
SET "_t=!_h!:!_m
SET "_t=!_t:00:=

)
)
)
)

EndLocal & SET %~1=%_t%


goto :EOF

A test with a delay of 94 sec

DEMO timer function


--------------------

Making some delay, please wait...

by Default : 9404
in Seconds : 94
Formatted : 01:34.05 (HH:MM:SS.CS)

Presione una tecla para continuar .

edited May 5 '16 at 13:14


Community ♦
1 1

answered May 18 '15 at 9:18


PHC
29 1

A small update for an alternative of


output format if we want that instead
of hh:mm:ss,cs change the format to

00h 00m 00s we need to change the


By using our site, you acknowledge
lines with: SET that you have read and understand our , , and our
. "_t=!_h!:!_m!:!_s!.!_cs!" SET
"_t=!_t:00:=!" and replace them
ith th f ll i d
https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 15/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
with the following code: IF
"%_f%" == "hms" ( SET "_t=!_h!h
!_m!m !_s!s" & SET
"_t=!_t:00h=!" & SET
"_t=!_t:00m=!" & SET "_t=!_t:
=!" ) ELSE ( SET
"_t=!_h!:!_m!:!_s!.!_cs!" & SET
"_t=!_t:00:=!" ) Now we can use
as a formatted parameter the
sentence "hms" so that the output
format would be 00h 00m 00s – PHC
May 18 '15 at 11:22

Aacini's latest code showcases an


awesome variable substitution
0 method.
It's a shame it's not Regional format
proof - it fails on so many levels.
Here's a short fix that keeps the
substitution+math method intact:

@echo off
setlocal EnableDelayedExpansion

set "startTime=%time: =0%" & rem Ave

set /P "=Any process here..."

set "endTime=%time: =0%" & rem AveYo

rem Aveyo: Regional format fix with


for /f "tokens=1-3 delims=0123456789
"DOT=%%k"

rem Get elapsed time:


set "end=!endTime:%DOT%=%%100)*100+1
set /A "elap=((((10!end:%COLON%=%%10
((((10!start:%COLON%=%%100)*60+1!%%1

rem Aveyo: Fix 24 hours


set /A "elap=!elap:-=8640000-!"

rem Convert elapsed time to HH:MM:SS


set /A
"cc=elap%%100+100,elap/=100,ss=elap%

echo Start: %startTime%


echo End: %endTime%
echo Elapsed: %hh:~1%%COLON%%mm:~1%
as regional
pause

"Lean and Mean" TIMER with


Regional format, 24h and mixed
input support
Adapting Aacini's substitution method
body, no IF's, just one FOR (my
regional fix)
By using our site, you acknowledge that you have read and understand our , , and our
1: File timer.bat placed somewhere in
.
%PATH% or the current dir

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 16/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow

@echo off & rem :AveYo: compact time


mixed input support
if not defined timer_set (if not "%~
"timer_set=%TIME: =0%") & goto :eof
(if not "%~1"=="" (call set "timer_e
setlocal EnableDelayedExpansion
for /f "tokens=1-6 delims=0123456789
CE=%%i&set DE=%%k&set CS=%%l&set DS=
set "TE=!timer_end:%DE%=%%100)*100+1
set/A "T=((((10!TE:%CE%=%%100)*60+1
set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss
endlocal & set "timer_end=%value%" &

Usage:
timer & echo start_cmds & timeout /t
3 & echo end_cmds & timer
timer & timer "23:23:23,00"
timer "23:23:23,00" & timer
timer "13.23.23,00" & timer
"03:03:03.00"
timer & timer "0:00:00.00" no & cmd
/v:on /c echo until
midnight=!timer_end!
Input can now be mixed, for those
unlikely, but possible time format
changes during execution

2: Function :timer bundled with the


batch script (sample usage below):

@echo off
set "TIMER=call :timer" & rem short
echo.
echo EXAMPLE:
call :timer
timeout /t 3 >nul & rem Any process
call :timer
echo.
echo SHORT MACRO:
%TIMER% & timeout /t 1 & %TIMER%
echo.
echo TEST INPUT:
set "start=22:04:04.58"
set "end=04.22.44,22"
echo %start% ~ start & echo %end% ~
call :timer "%start%"
call :timer "%end%"
echo.
%TIMER% & %TIMER% "00:00:00.00" no
echo UNTIL MIDNIGHT: %timer_end%
echo.
pause
exit /b

:: to test it, copy-paste both above and


below code sections

rem :AveYo: compact timer function w


support
:timer Usage " call :timer [input -
second call, saved to timer_end
if not defined timer_set (if not "%~
By using our site,"timer_set=%TIME:
you acknowledge that=0%") & goto
you have read:eof
and understand our , , and our
(if not "%~1"=="" (call set "timer_e
. setlocal EnableDelayedExpansion

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 17/18
1/29/2019 Calculate time difference in Windows batch file - Stack Overflow
for /f "tokens=1-6 delims=0123456789
CE=%%i&set DE=%%k&set CS=%%l&set DS=
set "TE=!timer_end:%DE%=%%100)*100+1
set/A "T=((((10!TE:%CE%=%%100)*60+1
set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss
endlocal & set "timer_end=%value%" &

edited May 23 '17 at 11:47


Community ♦
1 1

answered May 14 '17 at 20:24


AveYo
21 3

By using our site, you acknowledge that you have read and understand our , , and our
.

https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file 18/18