1

In one of my batch scripts I need to calculate the duration of an interval in a video file. First the user is asked to input the start and end times:

set /p StartPosition=Start position (HH:MM:SS):
set /p EndPosition=End position (HH:MM:SS):

Then, I would like the batch script to calculate the duration in between.

How can I subtract %StartPosition% from %EndPosition% like this, for example:

00:10:40 - 00:10:30 = 00:00:10

The reason why I can't figure out how to do this is because these numbers are separated by colons.

Edit: This question is different to this question because I do not need the scrip to treat the numbers as time values.

Community
  • 1
  • 1
Arete
  • 948
  • 3
  • 21
  • 48
  • 1
    Possible duplicate of [How to measure execution time of command in windows command line?](http://stackoverflow.com/questions/673523/how-to-measure-execution-time-of-command-in-windows-command-line) – JosefZ Mar 05 '17 at 00:55
  • 2
    What if the times were `11:05 - 10:45`? Would you expect an answer of `:20`? That is not "standard" math. It requires awareness of 60-seconds in a minute. – abelenky Mar 05 '17 at 01:04
  • 1
    You have to strip the leading zeros from each field for the set command to do the math correctly. Basically you will need to convert the entire time to seconds and then have a function that converts it back to hours minutes and seconds. Personally I would go with a hybrid batch file with some embedded Jscript. – Squashman Mar 05 '17 at 01:28

6 Answers6

15
@echo off
setlocal

set /p "StartPosition=Start position (HH:MM:SS): "
set /p "EndPosition=End position (HH:MM:SS):   "

set /A "ss=(((1%EndPosition::=-100)*60+1%-100)-(((1%StartPosition::=-100)*60+1%-100)"
set /A "hh=ss/3600+100,ss%%=3600,mm=ss/60+100,ss=ss%%60+100"

echo Duration=%hh:~1%:%mm:~1%:%ss:~1%

EDIT: Some explanations added

This program use the usual method to convert a time in HH:MM:SS format into a number of seconds via the standard formula: seconds = (HH*60+MM)*60+SS. However, the set /A command consider the numbers that start with 0 as written in octal base, and hence 08 and 09 would be invalid octal numbers. To avoid this problem, a digit 1 is placed before expand the number and a 100 is subtracted after, so if HH=08 then 1%HH%-100 correctly gives 8; that is:

set /A seconds = ((1%HH%-100)*60+1%MM%-100)*60+1%SS%-100

There are several methods to split a time given in HH:MM:SS format into its three parts. For example, if we take set EndPosition=HH:MM:SS as base, then we may use a for /F command this way:

for /F "tokens=1-3 delims=:" %%a in ("%EndPosition%") do (
   set /A "seconds=((1%%a-100)*60+1%%b-100)*60+1%%c-100"
)

In this program a different method is used. If we match the original EndPosition=HH:MM:SS string with the desired formula, we may construct this mapping scheme:

     HH       :      MM       :      SS

((1  HH  -100)*60+1  MM  -100)*60+1  SS  -100

In other words: if we replace the colons of the original string by -100)*60+1 and insert ((1 at beginning and -100 at end, we obtain the desired formula; that is:

set /A "seconds=((1%EndPosition::=-100)*60+1%-100"

This is a very efficient method that even allows to replace both EndPosition and StartPosition strings in the same formula (enclosing both parts in parentheses) and directly subtract them:

set /A "ss=(((1%EndPosition::=-100)*60+1%-100)-(((1%StartPosition::=-100)*60+1%-100)"

You may cancel the @echo off command and run the program to review the exact formula that is evaluated after the values of the variables are replaced. For example, when StartPosition=00:10:30 and EndPosition=00:10:40, this is the expression that is evaluated:

set /A "ss=(((100-100)*60+110-100)*60+140-100)-(((100-100)*60+110-100)*60+130-100)"

Just to complete this description, this is the "standard" way to evaluate the same formula using a for /F command:

for /F "tokens=1-6 delims=:" %%a in ("%EndPosition%:%StartPosition%") do (
   set /A "ss=(((1%%a-100)*60+1%%b-100)*60+1%%c-100)-(((1%%d-100)*60+1%%e-100)*60+1%%f-100)"
)

The opposite conversion from number of seconds to HH:MM:SS parts is straightforward:

HH=SS/3600, rest=SS%3600, MM=rest/60, SS=rest%60

However, each part in the result must be displayed with two digits, but this formatting may be achieved in a very simple way. Instead of insert three if commands that check if each part is less than 10 and insert a padding zero in such a case, the number 100 is just added to the parts (converting an 8 into 108, for example), and when each part is displayed the first digit is omitted (so just 08 is shown). This is a very efficient method to format numbers that may be performed in the same set /A command used to obtain the parts. For example:

set /A "hh=ss/3600+100,ss%%=3600,mm=ss/60+100,ss=ss%%60+100"

echo Duration=%hh:~1%:%mm:~1%:%ss:~1%

In this way, the conversion of two times into two number of seconds, their subtraction and the opposite conversion and formatting to HH:MM:SS is performed in two SET /A commands, that even may be written in a single, long line.

Output examples:

Start position (HH:MM:SS): 00:10:30
End position (HH:MM:SS):   00:10:40
Duration=00:00:10

Start position (HH:MM:SS): 00:10:45
End position (HH:MM:SS):   00:11:05
Duration=00:00:20
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • This is by far more elegant than I expected for an answer. Thanks a bunch! Although I realise batch scripting is probably not the syntax for this operation. – Arete Mar 05 '17 at 12:59
1

This is possible to do in pure batch by parsing each field as an independent string, then doing arithmetic on them. Many practical solutions call into some other program to do the date math.

The following code calls into PowerShell to use the .NET DateTime class to do the parsing for you.

C:\> set "StartPosition=00:10:30"
C:\> set "EndPosition=00:10:40"
C:\> PowerShell.exe -c "$span=([datetime]'%EndPosition%' - [datetime]'%StartPosition%'); '{0:00}:{1:00}:{2:00}' -f $span.Hours, $span.Minutes, $span.Seconds"
00:00:10

This executes two lines of PowerShell code; one to convert both times into DateTime objects and subtract them, and the other to output the result in the format you specified.

Community
  • 1
  • 1
Ryan Bemrose
  • 9,018
  • 1
  • 41
  • 54
  • @Arete what do you mean "batch only"? The line I put above is a batch file command that does what you want. It just happens to call into another Windows program to perform the calculation. – Ryan Bemrose Mar 05 '17 at 01:38
  • This is interesting! If an "extremely difficult" Batch file that solve this problem (like [this one](http://stackoverflow.com/a/42603985/778560)) uses two lines for the conversion and one line for the formatting, is this PowerShell solution "two thirds extremely difficult"? **`^_^`** Certainly, this PS solution is extremely slow when compared vs. the Batch file one... – Aacini Mar 05 '17 at 03:23
  • 1
    @Aacini Yes, you're very clever; you've created something in batch. You don't need to be an ass about it. I would argue this PowerShell solution is much more readable as the critical bits don't look like line noise. Re: speed, PS is quite comparable once the .NET framework is loaded. If speed really is critical, you need to drop batch and write an .exe anyway. – Ryan Bemrose Mar 05 '17 at 04:42
  • You opined at first that "a batch file solution is extremely difficult", but you deleted such comments later. Although "extremely difficult" is a subjective term, I think that such an opinion about a Batch solution that can be completed in 4 lines using a standard `for` command just shows a lack of knowledge about Batch files. When we have faced in other topics (like [this one](http://stackoverflow.com/questions/32417191/batch-file-to-delete-half-the-lines-of-a-text-file-at-random/32432287#32432287)) you have also criticized Batch files when you suggested a _non-requested_ PowerShell solution. – Aacini Mar 07 '17 at 02:13
  • It seems you think that the most important point to convince Batch users to use PowerShell is because Batch files are "bad", like if this was a presidential candidate debate! I invite you to read Batch file users opinions against PS at end of [this article](http://windowsitpro.com/powershell/break-your-batch-habit-and-move-powershell) or in [_What I Hate About PowerShell_](https://helgeklein.com/blog/2014/11/hate-powershell/) one. I am sorry, but I will continue using your same Batch-file adjetives in a counter-criticism against PS as long as you continue doing the same thing... – Aacini Mar 07 '17 at 02:14
  • When a person deletes a comment on SO (which happened before you responded) it is often an indication that they no longer consider what was written to be relevant. I am not going to defend a position that I no longer hold. – Ryan Bemrose Mar 08 '17 at 02:34
  • 2
    I agree there are pros and cons to every programming language, but Powershell is objectively superior to batch files in almost every measure: expressivity, readability, maintainability, interoperability, and learning curve. I make the assumption that not everybody who asks a batch file question (or visits this question later) has weighed the pros and cons of every scripting language available on the OS, but rather that they might be using batch as a "default" Windows scripting language. I want to make sure people in that situation understand that there are other options. – Ryan Bemrose Mar 08 '17 at 02:40
  • 1
    Whenever we have this discussion, your only argument against PS seems to be performance. I don't know what caused you to be such a batch file purist, @Aacini. I respect that you know a great deal about batch, and that you live and breathe its esoteric and inscrutable syntax. Neither I nor Microsoft believe it is the future, though, and I think you do a disservice by discouraging people from being made aware of other scripting options on their computers. – Ryan Bemrose Mar 08 '17 at 02:44
  • I think that presenting options to Batch file users is a good thing; please, continue doing it! What is wrong is that you criticize Batch with degrading terms when you present a _non-requested_ PowerShell solution. Are you trying to convince users that they are wrong if they prefer Batch? I personally prefer JScript, but I never posted a non-requested JScript solution with this phrase: "you must use JScript because Batch files are difficult, arcane and slow". Note that I never have said: "You should not use PowerShell"; I criticized _your PS solution_ as reply to your first criticism on Batch. – Aacini Mar 09 '17 at 00:53
  • Yes: PowerShell is more (_put any good adjetive you want here_) that Batch files, but this don't means it is the right choice in all cases, particularly when the problem to solve is simple, like this one. You should realize and accept that using the powershell.exe 465 KB size file (half the size of Google chrome.exe!) and a large .NET class just to obtain the same result of a 3-lines Batch file is something that have no sense! Your adjetives about PS are _opinions_, so I include here as reply some opinions of several Batch file users (not the mine!) extracted from the first link I gave before: – Aacini Mar 09 '17 at 00:53
  • "Don't get me started on Powershell syntax. That coupled with some peoples perverse pleasure in attempting to do the entire process all on one line, makes it a real PITA to get started in.", "Not to mention bat files just execute right out of the box when you double click, powershell's .ps1 files take all kinds of work (permissions, configuration, etc) to make them double click executable, future looks so bleak and so painful.", "I would also add the PowerShell syntax is more verbose and so different from any other command line (e.g. MS-DOS, UNIX, etc.) For example, after 25+ years of usage – Aacini Mar 09 '17 at 00:54
  • "dir /s/b" and "ls -al" are second nature to me whereas "gci -Recurse -Name" (which I had to look up) is not.", "Virtually every powershell example from here on the web that I've tried running don't work, I get nothing but line after line of red error text. not helpful. I've got libraries of vbscript that rock. wasn't difficult to learn, doesn't take a bunch of research and aggrevation to try to get running. I still have no idea why "no-powershell" scripts don't run. whats the freakin point. vbscripts / batch / hta's still get the job done.", "Absolutely no need to throw out something that – Aacini Mar 09 '17 at 00:54
  • works and works well. Powershell is great but I reject the "must" aspect. I have fellow techs that know both like myself and we choose tools based on the best fit for the job. It's a closed mind that says we should stop using something that still has place in our current tech.", "... stating that PowerShell is a real programming language is a stretch at best. The design of PowerShell is so convoluted that the "logic" makes no sense at all... I find the design of PowerShell to be mostly a joke. This is why many people stick with batch files. The construct makes much more sense that PowerShell". – Aacini Mar 09 '17 at 00:55
  • You may also read the article at the 2nd link where a very experienced software developer describe a series of things that _"are wrong with PowerShell"_: PowerShell’s operators are horrible... Having the backtick as escape character is just plain weird... Functions are called without parentheses, but .NET functions are called with parentheses... Uses dynamic scoping with copy on write (versus lexical scoping, which is what everybody else uses). If you have used other languages before, this is totally confusing. Even if you have not, this easily leads to errors that are really hard to find... – Aacini Mar 09 '17 at 00:55
0

Here's a working prototype:

@echo off 

set T1=00:10:45
set T2=00:11:05

set HOUR1=%T1:~,2%
set MIN1=%T1:~3,-3%
set SEC1=%T1:~-2%

set HOUR2=%T2:~,2%
set MIN2=%T2:~3,-3%
set SEC2=%T2:~-2%

set /A TOTAL_SEC1=%HOUR1%*3600+%MIN1%*60+SEC1
set /A TOTAL_SEC2=%HOUR2%*3600+%MIN2%*60+SEC2
set /A DIFF=%TOTAL_SEC2%-%TOTAL_SEC1%

echo %DIFF%

Output:

20

Its not complete, but its a reasonable start.

abelenky
  • 63,815
  • 23
  • 109
  • 159
0

I think, @Aacini has cleared Everything here. He got you, Before I Do. But, I want to Improved on him as - by using For Loop to make code Easier.

Note: Everything after 'REM' is a Comment for the sake of understanding easily...
All You need to DO is Copy It into Your Batch File. And, Use it as follows (in your main code):

Syntax: Call :Time [Your Time 1] [Operation] [Your Time 2]

And, You can Now apply - any operation - including 'Addition, Substraction, Division, Multiplication' ;) The Time Function
--------------Copy the Below Code----------

:Time [Start_Time] [Operation] [End_Time]
SetLocal EnableDelayedExpansion
REM Creating a portable Function for your Job. :)

REM Reading Start-time...
For /F "Tokens=1,2,3 Delims=:" %%A in ("%~1") Do (
Set _Start_Hour=%%A
Set _Start_Min=%%B
Set _Start_Sec=%%C
)

REM Reading End-time...
For /F "Tokens=1,2,3 Delims=:" %%A in ("%~3") Do (
Set _End_Hour=%%A
Set _End_Min=%%B
Set _End_Sec=%%C
)

REM Removing leading Zero's - if any... 'CMD assumes it as octal - otherwise'
For %%A In (Hour Min Sec) Do (
    For %%B In (Start End) Do (
        IF /I "!_%%B_%%A:~0,1!" == "0" (Set _%%B_%%A=!_%%B_%%A:~1!)
        )
)

REM Applying Operation on the given times.
For %%A In (Hour Min Sec) Do (Set /A _Final_%%A=!_Start_%%A! %~2 !_End_%%A!)

REM Handling a little Exceptional errors! - due to the nature of time (60 sec for a min.)
SET _Extra_Hour=0
SET _Extra_Min=0

REM Two Cases can arise in each part of time...
:Sec_loop
IF %_Final_Sec% GTR 59 (Set /A _Extra_Min+=1 & Set /A _Final_Sec-=60 & Goto :Sec_loop)
IF %_Final_Sec% LSS 0 (Set /A _Extra_Min-=1 & Set /A _Final_Sec+=60 & Goto :Sec_loop)

Set /A _Final_Min+=%_Extra_Min%

:Min_loop
IF %_Final_Min% GTR 59 (Set /A _Extra_Hour+=1 & Set /A _Final_Min-=60 & Goto :Min_loop)
IF %_Final_Min% LSS 0 (Set /A _Extra_Hour-=1 & Set /A _Final_Min+=60 & Goto :Min_loop)

Set /A _Final_Hour+=%_Extra_Hour%

REM Saving Everything into a Single Variable - string.
Set _Final_Time=%_Final_Hour%:%_Final_Min%:%_Final_Sec%

REM Displaying it on the console. ;)
Echo.%_Final_Time%
Goto :EOF
--------------End OF Code----------------------

You can Also visit, my Website - based on Batch Programming. (www.thebateam.org) You'll find alot of stuff there - to help you out. :) Here's the Final Output - When I saved the Code in Answer.bat File

  • 1
    Multiplication and division will not work without significant changes such as converting the start and end times to seconds. With only that change, multiplication and division could work, albeit with awkward syntax. (00:20:00 * 00:00:02 for 20 mins * 2?) Also, output should be padded with zeros. – user2033427 Mar 05 '17 at 08:00
  • :o Thats a good hint about fixing a bug. and, Padding with the zeros is not a difficult task all I need is to add few more lines to check the width of the final output and add zeros if they are single digits. Although, @Aacini has fixed everything here. I'm too gonna follow his short and amazing solution. :) – KaranVeer Chouhan Mar 06 '17 at 00:02
0

To offer a concise alternative to Ryan Bemrose's helpful, PowerShell-based answer:

:: Sample variable values.
set "StartPosition=00:10:30"
set "EndPosition=00:10:40"

:: Use PowerShell to perform the calculation, 
:: using the .NET System.Timespan ([timespan]) type.
powershell -c \"$([timespan] '%EndPosition%' - '%StartPosition%')\"

Yes, you pay a performance penalty for invoking the PowerShell CLI, but I invite you to compare this solution to Aacini's clever, but highly obscure batch-language-only solution in terms of readability and conceptual complexity.

Generally speaking:

  • cmd.exe is a shell and, historically, shells have provided very limited language capabilities themselves, as their focus was on calling built-in or external commands.

    • cmd.exe's language, as used in batch files (.cmd, .bat) is very limited, and saddled with many counterintuitive behaviors that can't be fixed so as not to break backward compatibility.

      • Over the decades, users have learned to stretch the language to its limits, coming up with many clever techniques to squeeze more functionality out of it. While helpful if you're stuck on pre-PowerShell systems (virtually extinct at this point) or you must use batch files and performance is paramount (rarely the case), the obscurity of these techniques makes them both hard to understand and to remember.
    • cmd.exe's successor, PowerShell, with its .ps1 scripts, offers a far superior language that offers virtually unlimited access to .NET functionality and COM.

      • PowerShell too has its fair share of counterintuitive behaviors that can't be fixed, but, by and large, it is a far more capable and predictable language than the batch language; some of its undeniable, but unavoidable complexity comes from having to talk to multiple worlds (.NET, COM, WMI) while still also acting as a shell (with respect to calling external programs and the shell-like syntax of its built-in command as well as user-defined ones).
  • Here, the batch file uses a call an external program, powershell.exe, the PowerShell CLI, to delegate the task at hand to its superior language.

    • Calling the PowerShell CLI is expensive in terms of performance, but offers a way to perform tasks that batch files either cannot, or can only do with much more effort and/or highly obscure techniques.

Of course, needing to "speak" both the batch language and PowerShell to implement a given task adds complexity of its own, so the logical progression is to implement the entire task in PowerShell (in a .ps1 script).

  • Unfortunately, PowerShell puts up some road blocks here, in the name of security:

    • In workstation editions of Windows, execution of scripts is disabled by default, and requires a one-time call such as the following to enable it (see this answer for background information):

      Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
      
    • .ps1 scripts - unlike batch files - cannot be executed directly from outside PowerShell, notably not by double-clicking in File Explorer or from a cmd.exe session.

      • From inside a PowerShell session that is not a concern, but if you do need this capability in a given scenario, a simple workaround is to create a companion batch file with the same base file name as the .ps1 script (e.g., foo.cmd in the same directory as the target PowerShell script, foo.ps1, with the following, generic content:

        @powershell -noprofile -file "%~dpn0.ps1"
        
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

When setlocal enableextensions enabledelayedexpansion %time% and %date% may return the same value, to avoid use:

for /F "usebackq delims=" %%T in (`echo "^!time^!"`) do set _start=%%T

consume time

for /F "usebackq delims=" %%T in (`echo "^!time^!"`) do set _stop=%%T

then use !start! and !stop! variables

ugo
  • 284
  • 1
  • 2
  • 10