Time Formatting

Share your advanced PureBasic knowledge/code with the community.
chris319
Enthusiast
Enthusiast
Posts: 782
Joined: Mon Oct 24, 2005 1:05 pm

Time Formatting

Post by chris319 »

This program will be for adding times in minutes and seconds and presenting the output in an attractive mm:ss format. It is part of a larger work in progress intended for adding segment times of TV programs in minutes and seconds (all segment times are presumed to be under one hour). The finished program will convert segment times to seconds, add the number of seconds and display the result in mm:ss format.

You would think this could be done in Excel, but Excel gives inaccurate results when adding segment times. I have tried different time formats in Excel but no joy.

Suggestions welcome.

Code: Select all

Global time$,seconds

Procedure ToSeconds(time$)

seconds=Val(StringField(time$,1,":")) *60 ;CONVERT MINUTES TO SECONDS

seconds+Val(StringField(time$,2,":"))

;Debug seconds

EndProcedure

Procedure FormatTimestr(seconds)
;mins = Val(StringField(time$,1,":"))
mins = Int(seconds / 60)

secs = seconds - (mins * 60)

If secs < 10: sec$ = "0" + Str(secs) ;PAD WITH LEADING 0
Else
sec$ = Str(secs)
EndIf

If mins > 0 ;DROP LEADING 0
Debug Str(mins) + ":" + sec$
Else
Debug ":" + sec$
EndIf

EndProcedure

;ToSeconds ("1:30")

FormatTimestr(121)
Dude
Addict
Addict
Posts: 1907
Joined: Mon Feb 16, 2015 2:49 pm

Re: Time Formatting

Post by Dude »

chris319 wrote:Suggestions welcome

Code: Select all

FormatTimestr(121) ; 2:01
My version:

Code: Select all

Procedure.s FormatTimestr(secs)
  If secs<0
    t$="?:??"
  Else
    t$=FormatDate("%hh:%ii:%ss",secs)
    t$=LTrim(Mid(t$,FindString(t$,":")+1),"0")
    If Left(t$,1)=":" : t$="0"+t$ : EndIf
  EndIf
  ProcedureReturn t$
EndProcedure

Debug FormatTimestr(-1) ; ?:??
Debug FormatTimestr(0)  ; 0:00
Debug FormatTimestr(1)  ; 0:01
Debug FormatTimestr(59) ; 0:59
Debug FormatTimestr(60) ; 1:00
Debug FormatTimestr(61) ; 1:01
Debug FormatTimestr(121); 2:01
chris319
Enthusiast
Enthusiast
Posts: 782
Joined: Mon Oct 24, 2005 1:05 pm

Re: Time Formatting

Post by chris319 »

Negative seconds would be an error.
Dude
Addict
Addict
Posts: 1907
Joined: Mon Feb 16, 2015 2:49 pm

Re: Time Formatting

Post by Dude »

My code checks for negatives. Comparison:

Code: Select all

; Your code:
Debug FormatTimestr(-121) ; ":0-1"

Code: Select all

; My code:
Debug FormatTimestr(-121) ; "?:??"
Or you could just not call the procedure if the seconds are negative (do a pre-test).
Post Reply