sec2hms in pb

Share your advanced PureBasic knowledge/code with the community.
z3phir2003
User
User
Posts: 49
Joined: Wed Jan 12, 2005 3:50 pm

sec2hms in pb

Post by z3phir2003 »

Code updated For 5.20+

i needed a procedure to transform seconds in h:m:s with padding 0 optional (example without padding 1:2:3 with padding 01:02:03)

if anyone has something better please feal free to post it here or make mine better or corect bugs if any

maybe someone else needs something like this so i here it is

Code: Select all

Procedure.s sec2hms(sec$,padding=1)
  hours=Int(Val(sec$)/3600)
  minutes = Int(Val(sec$) / 60) % 60
  seconds = Int(Val(sec$)) % 60 
  If padding
    If hours < 10
       hours$="0"+Str(hours)
    ElseIf hours = 0
       hours$="00"
    Else
       hours$=Str(hours)
    EndIf
    If minutes < 10
       minutes$ = "0" + Str(minutes)
    ElseIf minutes = 0
       minutes$ = "00"
    Else
       minutes$ = Str(minutes)
    EndIf  
    If seconds < 10
       seconds$ = "0" + Str(seconds)
    ElseIf seconds = 0
       seconds$ = "00"
    Else 
       seconds$ = Str(seconds)
    EndIf  
  Else
    hours$=Str(hours)
    minutes$ = Str(minutes)
    seconds$ = Str(seconds)
  EndIf
  hms$=hours$+":"+minutes$+":"+seconds$
  ProcedureReturn hms$
EndProcedure
Phoenix
Enthusiast
Enthusiast
Posts: 141
Joined: Sun Sep 04, 2005 2:25 am

Re: sec2hms in pb

Post by Phoenix »

If you don't mind padding then it can be done as short as this.......

Code: Select all

Procedure.s sec2hms(sec)
  ProcedureReturn FormatDate("%hh:%ii:%ss",sec)
EndProcedure
; 300 seconds = 5 minutes
Debug sec2hms(300)
Dare
Addict
Addict
Posts: 1965
Joined: Mon May 29, 2006 1:01 am
Location: Outback

Post by Dare »

Yeta way:

Code: Select all

Procedure.s HMS(secs.l, padding.l = #True)
  Protected wrk.s
  Protected i.l
  wrk = FormatDate("%hh:%ii:%ss",secs)
  If Not padding
    wrk = ReplaceString(wrk,":0",":")
    If Left(wrk,1)="0"
      wrk = Mid(wrk,2,$0FF)
    EndIf
  EndIf
  ProcedureReturn wrk
EndProcedure

Debug HMS(0)
Debug HMS(0,#False)
Debug HMS(2)
Debug HMS(2,#False)
Debug HMS(20)
Debug HMS(20,#False)
Debug HMS(120)
Debug HMS(120,#False)
Debug HMS(1200)
Debug HMS(1200,#False)
Debug HMS(7200)
Debug HMS(7200,#False)
Debug HMS(72000)
Debug HMS(72000,#False)
Dare2 cut down to size
Post Reply