0

I am attempting to create a Batch program with the code here:

@echo off
set "DVAR=%1"
set STARTTIME=%TIMEA: =0%
set ENDTIME=%TIME: =0%
set /A STARTTIME=(1%STARTTIME:~0,2%-100)*360000 + 
(1%STARTTIME:~3,2%-100)*6000 
+ (1%STARTTIME:~6,2%-100)*100 + (1%STARTTIME:~9,2%-100)
set /A ENDTIME=(1%ENDTIME:~0,2%-100)*360000 + (1%ENDTIME:~3,2%-100)*6000 + 
(1%ENDTIME:~6,2%-100)*100 + (1%ENDTIME:~9,2%-100)
set /A DURATION=%ENDTIME%-%STARTTIME%
if %ENDTIME% LSS %STARTTIME% set /A DURATION=%STARTTIME%-%ENDTIME%
set /A DURATIONH=%DURATION% / 360000
set /A DURATIONM=(%DURATION% - %DURATIONH%*360000) / 6000
set /A DURATIONS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000) / 100
set /A DURATIONHS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000 - 
%DURATIONS%*100)
if %DURATIONH% LSS 10 set DURATIONH=0%DURATIONH%
if %DURATIONM% LSS 10 set DURATIONM=0%DURATIONM%
if %DURATIONS% LSS 10 set DURATIONS=0%DURATIONS%
if %DURATIONHS% LSS 10 set DURATIONHS=0%DURATIONHS%
if not defined dvar (
    echo Your current session has lasted 
%DURATIONH%:%DURATIONM%:%DURATIONS%.%DURATIONHS%.
) else (
    for /f "delims=" %%i in ('echo 
%DURATIONH%:%DURATIONM%:%DURATIONS%.%DURATIONHS%') do set %dvar%=%%i
)

to find the time elapsed between a variable TIMEA and the current time. However, if I run it (calling it from within a Batch file) 5 seconds after TIMEA was defined, I get:

Your current session has lasted .

And after running it again (7 seconds after TIMEA was defined), I get:

Your current session has lasted 00:00:05.00.

And again:

Your current session has lasted 00:00:07.00.

The output seems to be "backed up" by one program call. Any solutions?

Nathan Kronew
  • 11
  • 1
  • 1
  • 3
  • Where does the lone parenthesis before `if not defined dvar (` come from? – AlexP Oct 29 '17 at 23:47
  • I suspect you've over-pruned your code. Inserting a fixed (past) time as `timea` yields no error and the correct result. What is the purpose of `dvar`? Why the negative test? Your `duration` is set incorrectly for `endtime` lss `starttime` - it should be (subtract 24 hours) - or better, `if %duration% lss 0 set /a duration+=24*360000` – Magoo Oct 30 '17 at 01:11
  • `DVAR` is used so that if you were to run `session timeb` and then later `session timec`, you could have two different variables that would imply two different things. – Nathan Kronew Oct 30 '17 at 03:16
  • I suggest you to review this answer: https://stackoverflow.com/questions/9922498/calculate-time-difference-in-windows-batch-file/9935540#9935540 – Aacini Oct 30 '17 at 13:50

0 Answers0