Seconds to Time

edited May 12 in RAPID Programming
I have this function that converts seconds (num) to hours and minutes (num:num).

FUNC string SecondtoTime(num s)
VAR num seconds:=0;
VAR num minutes:=0;
VAR num hours:=0;

     IF s>=60 THEN
         minutes:= s DIV 60;
         seconds:= s MOD 60;
     IF minutes >= 60 THEN
        hours:= minutes DIV 60;
        minutes:= minutes MOD 60;
RETURN NumToStr(hours,0) + ":" +  NumToStr(minutes,0);

It works great until you input a time in seconds that is less than 10 minutes into the hour, for example 5:04 or 7:09 would end up being printed as 5:4 and 7:9 respectively.  I know this has something to do with the inputs being divisible by 60 so the MOD returns 0 as there is no can I force it to add a 0 to complete the time format? 


  • In other words, I am looking for a RAPID command that allows me to prepend a 0..I can't seem to find anything in the manual that allows you to do this. 
  • jmf
    jmf South Africa
    Instead of DIV try minutes:= s / 60; 
  • Thanks for the suggestion, I implemented it but the issue with the missing 0 for minutes below 10 persists. 
  • I have found the solution now, the trick is to add another IF statement at the bottom of the function. Instead of:

    RETURN NumToStr(hours,0) + ":" + NumToStr(minutes,0);

    You need: 

    IF minutes < 10 THEN

    RETURN NumToStr(hours,0) + ":" + "0" + NumToStr(minutes,0);


    RETURN NumToStr(hours,0) + ":" + NumToStr(minutes,0);