Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a int variable into a mm:ss

Can anyone help me how to format an int variable in delphi into a minute:seconds??

sample: myVar := 19;

my label caption should display 00:19

any idea anyone? thanks

like image 697
Tony Avatar asked Feb 07 '12 10:02

Tony


5 Answers

This will avoid any errors for seconds values that overflow into hours.

var
  secs: integer;
  str: string;
begin
  secs := 236;
  // SecsPerDay comes from the SysUtils unit.
  str := FormatDateTime('nn:ss', secs / SecsPerDay));

  // If you need hours, too, just add "hh:" to the formatting string
  secs := 32236;
  str := FormatDateTime('hh:nn:ss', secs / SecsPerDay));
end;
like image 107
Brad Stowers Avatar answered Nov 09 '22 00:11

Brad Stowers


Assuming the myVar contains number of seconds:

label1.Caption := Format('%.2d:%.2d', [myVar div 60, myVar mod 60]);
like image 34
ain Avatar answered Nov 08 '22 23:11

ain


You should use FormatDateTime method like this:

procedure TForm1.FormCreate(Sender: TObject);
const MyConst: Integer = 19;
begin
  Caption:=FormatDateTime('nn:ss', EncodeTime(0, MyConst div 60, MyConst mod 60, 0));
end;
like image 4
Narcís Calvet Avatar answered Nov 08 '22 23:11

Narcís Calvet


Expanding onto Brad's answer, I've wrapped this into a function which detects if the time is over an hour, and automatically shows hours if so. Otherwise, if it's less than an hour, it doesn't show the hours. It also has an optional parameter to define whether to show a leading zero on the hours and minutes, depending on your preference (i.e. 03:06:32 vs 3:6:32). This makes it a little more human-readable.

function SecsToTimeStr(const Secs: Integer; const LeadingZero: Boolean = False): String;
begin
  if Secs >= SecsPerHour then begin
    if LeadingZero then
      Result := FormatDateTime('hh:nn:ss', Secs / SecsPerDay)
    else
      Result := FormatDateTime('h:n:ss', Secs / SecsPerDay)
  end else begin
    if LeadingZero then
      Result := FormatDateTime('nn:ss', Secs / SecsPerDay)
    else
      Result := FormatDateTime('n:ss', Secs / SecsPerDay)
  end;
end;

However, there are many different possible preferences with displaying a time period, which is up to you to decide. I won't cover all those possible ways here.

enter image description here

like image 2
Jerry Dodge Avatar answered Nov 09 '22 00:11

Jerry Dodge


If you are sure you only want minutes and seconds - a quick solution could be:

Format('%d:%d',[(myVar div 60), (myVar mod 60)]);

Same solution as already proposed ... :-)

like image 1
Bimmer_R Avatar answered Nov 08 '22 23:11

Bimmer_R