2012-02-07 136 views
3

任何人都可以帮助我如何在delphi中将int变量格式化为一分钟:秒?将int变量格式化为mm:ss

样本: myVar:= 19;

我的标签标题应显示00:19

任何想法的人?感谢

+0

没有提供真的,所有我需要的是将它与格式“MM:SS”这种格式 – Tony 2012-02-07 11:03:15

回答

7

假设myVar包含的秒数:

label1.Caption := Format('%.2d:%.2d', [myVar div 60, myVar mod 60]); 
+0

它说数组类型必需 – Tony 2012-02-07 11:10:14

+0

有在我的例子格式参数之间缺少逗号,现在固定。哦,看起来像SimaWB打我解决它,谢谢。 – ain 2012-02-07 11:13:11

+0

感谢你,,,你刚刚错过了,所以这就是为什么它显示阵列所需的错误发生,谢谢 – Tony 2012-02-07 11:13:14

4

你应该使用FormatDateTime method这样的:

procedure TForm1.FormCreate(Sender: TObject); 
const MyConst: Integer = 19; 
begin 
    Caption:=FormatDateTime('nn:ss', EncodeTime(0, MyConst div 60, MyConst mod 60, 0)); 
end; 
+0

感谢这些。 – Tony 2012-02-07 11:15:05

+0

如果MyConst> 60,会出现'EConvertError'。更好地使用它:'Caption:= FormatDateTime('nn:ss',IncSecond(0,myVar));'(包括'DateUtil') – kobik 2012-02-07 11:17:56

+0

@kobik我已经在我的代码片段 – 2012-02-07 11:18:24

1

如果您确信您只想分钟和秒 - 一个快速的解决方案可能是格式('%d:%d',[(myVar div 60),(myVar mod 60)]);

相同的溶液已经提出了... :-)

+0

谢谢,除以更容易。生病做 – Tony 2012-02-07 11:19:18

10

这将避免任何错误行为溢出到小时秒值。

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; 
+1

+1此解决方案很容易理解,并将与任何输入值一起使用。这也是最灵活的一个。 – 2012-02-07 15:56:11

0

扩大到布拉德的答案,我裹成检测,如果时间超过一个小时,并自动显示小时,如果这样的功能这一点。否则,如果不到一个小时,则不显示小时数。它还有一个可选参数,用于根据您的偏好定义是否在小时和分钟上显示前导零(即03:06:32 vs 3:6:32)。这使得它更容易阅读。

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; 

不过,也有与显示时间,这是由你来决定许多不同的可能偏好。我不会在这里介绍所有可能的方法。

enter image description here

相关问题