我从数据库接收以秒为单位的时间值,我想将其计算为可读时间。这些是消息的总激活时间,因此我不必考虑任何leap年。
我要计算的秒数可能超过24小时,所以hhh:mm:ss
。我用它来格式化实时图表中图表上的标签。在我的代码中,我使用以下代码进行计算:
public Func<double, string> Formatter { get; set; }
Formatter = value => (((value - (value % 3600)) / 3600) + ":" + (((value % 3600) - (value % 60)) / 60) + ":" + (value % 60));
这很好,但有时会导致:
222:3:4
但是我想要的是:
222:03:04
我找到了以下代码来制作string.Format
,但我不知道在使用Func<>
时如何应用此代码:
static string Method1(int secs)
{
int hours = secs / 3600;
int mins = (secs % 3600) / 60;
secs = secs % 60;
return string.Format("{0:D2}:{1:D2}:{2:D2}", hours, mins, secs);
}
当我使用string.Format
计算超过24小时的时间时,如何应用此public Func<double, string>
。
答案 0 :(得分:1)
您可以在public Func<double, string>
中使用string.Format,只需将值用作参数即可,而不是单个字符串:
Formatter = value => string.Format("{0:D2}:{1:D2}:{2:D2}", (int)(value - (value % 3600)) / 3600, (int)((value % 3600) - (value % 60)) / 60, (int)value % 60);
或者,如上所述,最好使用内置函数。
答案 1 :(得分:0)
您应该使用标准的TimeSpan格式器之一。可能是“ g”:
static string Method1(int secs)
{
var ts = new TimeSpan.FromSeconds(secs);
return ts.Format('g');
}