Converting seconds to HH:MM:SS

In the November class here in Austin, one of the students had a project requirement to display the number of seconds for an countdown timer. His problem was that the timer was an integer tag for number of seconds, but the requirement was to display it in HH:MM:SS format. I threw something together quickly, but it admittedly wasn't the wasn't the most efficient method. So after a little tweaking, came up with a couple of ways for displaying the conversion. 

A few helpful things to know about the code is that both methods use both the Mod() and Format() Arithmetic functions. Mod() is a function that will divide two numbers and return the remainder. Format("%02d",[value]) will format the output as a two-digit number, regardless of value.

The number of seconds is held in an integer tag named iNumSec.



The first method was to run the following code in the Screen Script (Screen_WhileOpen() subroutine). This will write the value to a separate string tag (strConvertedTime), which can then be displayed on the screen using a Text object or Rectangle caption. In this case I used the MOD VbScript function instead of the built-in, but it works the same way.

'This procedure is executed continuously while this screen is open.

Sub Screen_WhileOpen()

       Dim NumHour, NumMin, NumSec

     ' calculates whole hours

      NumHour = $iNumSec\3600

     ' calculates the remaining number of seconds

      NumSec = $iNumSec Mod 3600

     ' calculates the whole number of minutes

      NumMin = NumSec\60

     ' calculates the remaining number of seconds

      NumSec = NumSec Mod 60

     ' returns the value to a string tag

      $strConvertedTime = $Format("%02d", NumHour) & ":" & $Format("%02d", NumMin) & ":" & $Format("%02d", NumSec)

 End Sub


The next method writes the output directly into the caption of an object (such as a rectangle). This was a little more challenging, since I was unable to build values directly based on other calculations like the VbScript above.


One function invaluable for this was the Trunc([Value]) function. This built-in function strips any decimals away from a whole number, leaving only the whole number, avoiding any issues with rounding.

Here is the caption placed in the rectangle...

[Format("%02d",Trunc(iNumSec/3600))] :[Format("%02d",((Trunc(iNumSec-(Trunc(iNumSec/3600)*3600)))/60))] :[Format("%02d",Mod(iNumSec-(Trunc(iNumSec/3600)*3600),60))]

To make this easier to read, here is a breakdown by conversion


Hours: [Format("%02d",Trunc(iNumSec/3600))]

:

Minutes: [Format("%02d",((Trunc(iNumSec-(Trunc(iNumSec/3600)*3600)))/60))]

:

Seconds: [Format("%02d",Mod(iNumSec-(Trunc(iNumSec/3600)*3600),60))]

If anyone can come up with a more efficient method please feel free to reply.