开发者

Briefest way to display TimeSpan value as an elapsed time e.g. 1:45:33

I'd like an easy way to display any TimeSpan as an elapsed time without using loops or custom logic

e.g.

hours : minutes : seconds

I'm sure there must be a .NET built-in or format string that applies, however开发者_运维百科 I'm unable to locate it.


The question itself isn't a duplicate but the answer, I assume, is what you are looking for - Custom format Timespan with String.Format. To simplify your solution further you could wrap that functionality up in an extension method of Timespan.


What's wrong with TimeSpan.ToString()?

EDIT: You can use a DateTime as an intermediate formatting store:

TimeSpan a = new TimeSpan(1, 45, 33);
string s = string.Format("{0:H:mm:ss}", new DateTime(a.Ticks));
Console.WriteLine(s);

Not pretty but works.


You can use:

TimeSpan t = TimeSpan.FromSeconds(999);
string s = t.ToString("c");  // s = "00:16:39"

For custom formats, see this MSDN page.


Here is a method I use for custom formatting:

TimeSpan Elapsed = TimeSpan.FromSeconds(5025);
string Formatted = String.Format("{0:0}:{1:00}:{2:00}",
    Math.Floor(Elapsed.TotalHours), Elapsed.Minutes, Elapsed.Seconds);
// result: "1:23:45"

I don't know if that qualifies as "without custom logic," but it is .NET 3.5 compatible and doesn't involve a loop.


Use This: .ToString()

According to MSDN, the default format this displays is [-][d.]hh:mm:ss[.fffffff]. This is the quickest and easiest way to display TimeSpan value as an elapsed time e.g. 1:45:33

If you have days, fractions of a second, or a negative value, use a custom format string as described in MSDN. This would look like .ToString(@"hh\:mm\:ss")

Example:

TimeSpan elapsed = new TimeSpan(0, 1, 45, 33);
Console.WriteLine(elapsed.ToString());             //outputs: "1:45:33"
Console.WriteLine(elapsed.ToString(@"hh\:mm\:ss"));//outputs: "1:45:33"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜