Convert time to HH:MM string

Posted by Jenny on March 17, 2007

In Reply to Re: Timer posted by Paul Collings on March 17, 2007

: I don't want the edit box to display the current/real time. I want the timer to start at 00.00 and be updated every minute. With the edit box displaying the time elapsed in HH:MM, for example 03:56, as you suggested. In a 24 hours format please.

In the example below Timer1 is enabled when Button1 is clicked. So, at the start of the operation, you must have Timer1.Enabled := False (in the Object Inspector or by code at runtime). Setting the Timer1.Interval to 1000 will update the edit box every second. You could add a second button to stop the timer.

Because the TimeToStr function uses Windows' local settings, that gives a different result on different computers. So let's write or own conversion code :-)

  StartDTime: TDateTime;

procedure TForm1.Button1Click(Sender: TObject);
  StartDTime := Now; // store starting date and time
  Timer1.Enabled := True;

procedure TForm1.Timer1Timer(Sender: TObject);
  Hour, Min, Sec, MSec: word;
  HH, MM: string;
  DecodeTime(Now - StartDTime, Hour, Min, Sec, MSec);
  HH := IntToStr(Hour);
  if Length(HH) = 1 then HH := '0' + HH;
  MM := IntToStr(Min);
  if Length(MM) = 1 then MM := '0' + MM;
  Edit1.Text := HH + ':' + MM;


Related articles


Follow Ups