Luka Sinobad
Luka Sinobad

Reputation: 23

Delphi Stopwatch time format

procedure TForm1.TimerSWTimer(Sender: TObject);
var
 Hour, Min, Sec, MSec: word;
begin
 ElapsedTime := Time - StartTime + Totaltime ;
 DecodeTime(elapsedtime, Hour, Min, Sec, MSec);
 LabelSW.Text := IntToStr(Hour)  + ':'+ IntToStr(Min) + ':'+ IntToStr(Sec) + ':' + IntToStr(Msec);
end;

This is the code for stopwatch that I am trying to implement into my application, the main problem is that the time format shown on the label is 0:0:0:0, and I would like it to be 00:00:00:000 for hours, minutes, seconds and miliseconds. I have tried numerous things and codes that i found online but none of it helped me.

When i start the stopwatch, the time goes like this 0:0:0:1, than 0:0:0:10, 0:0:0:100, and after a full second miliseconds go to 1 decimal (1 instead 001). Same thing for hours, minutes and seconds, they are shown on 1 decimal until they reach 10 (9 instead 09)..

I have tried:

If any of you good chaps can help, I would greatly appreciate it.

Cheers.

Upvotes: 1

Views: 9901

Answers (1)

LU RD
LU RD

Reputation: 34919

See http://docwiki.embarcadero.com/Libraries/en/System.SysUtils.Format

labelSW.Text := Format('%2.2u:%2.2u:%2.2u:%3.3u',[Hour,Min,Sec,MSec]);

The precision specifier makes left padding with zeroes.


Using the RTL TStopwatch advanced record in System.Diagnostics, it gets a little easier:

uses
  System.SysUtils,
  System.Diagnostics;

var
  sw: TStopwatch;
...
sw := TStopwatch.StartNew;  // Start measuring time
...
procedure TForm1.TimerSWTimer(Sender: TObject);
begin
  LabelSW.Text := 
    FormatDateTime('hh:nn:ss:zzz',sw.ElapsedMilliseconds/MSecsPerDay); 
end;

Upvotes: 10

Related Questions