Problem
What is the appropriate method for formatting TimeSpan objects into a custom format string?
Asked by Hosam Aly
Solution #1
Please notice that this solution is only for.Net 4.0 and higher. Please see JohannesH’s response if you wish to format a TimeSpan in.Net 3.5 or lower.
In.Net 4.0, custom TimeSpan format strings were introduced. The MSDN Custom TimeSpan Format Strings page has a complete list of available format specifiers.
An example timespan format string is as follows:
string.Format("{0:hh\\:mm\\:ss}", myTimeSpan); //example output 15:36:15
(UPDATE) Here’s an example of string interpolation in C# 6:
$"{myTimeSpan:hh\\:mm\\:ss}"; //example output 15:36:15
The “:” character must be escaped with a “” (which must be escaped unless you’re using a verbatim string).
The “:” and “.” characters in a format string are explained in this excerpt from the MSDN Custom TimeSpan Format Strings page:
Answered by Doctor Jones
Solution #2
You could use the following for.NET 3.5 and lower:
string.Format ("{0:00}:{1:00}:{2:00}",
(int)myTimeSpan.TotalHours,
myTimeSpan.Minutes,
myTimeSpan.Seconds);
Code extracted from a bytes answer by Jon Skeet
See DoctaJonez’s response for.NET 4.0 and higher.
Answered by JohannesH
Solution #3
Making a DateTime object and using it for formatting is one option:
new DateTime(myTimeSpan.Ticks).ToString(myCustomFormat)
// or using String.Format:
String.Format("{0:HHmmss}", new DateTime(myTimeSpan.Ticks))
This is how I’m used to doing things. I’m hoping for a better solution.
Answered by Hosam Aly
Solution #4
Simple. Make use of TimeSpan. ToString with the characters c, g, or G. MSDN has further information.
Answered by KKK
Solution #5
I’d recommend
myTimeSpan.ToString("hh\\:mm\\:ss");
Answered by Shehab Fawzy
Post is based on https://stackoverflow.com/questions/574881/how-can-i-string-format-a-timespan-object-with-a-custom-format-in-net