Starting in .NET 4.0, it is possible to use custom formatting of TimeSpan objects. For .NET 3.5 or lower, refer to JohannesH's answer for alternative formatting options.
Custom TimeSpan format string allows precise control of output. The MSDN Custom TimeSpan Format Strings page provides a comprehensive reference of the available format specifiers.
To format a TimeSpan object using a custom format string, use the String.Format method as follows:
<code>string.Format("{0:hh\:mm\:ss}", myTimeSpan);</code>
This example format string will output "15:36:15" for a TimeSpan with the specified value.
Please note that the ":" character in the format string must be escaped with "". This is to distinguish it from TimeSpan delimiters.
C# 6 string interpolation provides a more concise syntax for formatting strings. The following example uses string interpolation to achieve the same result as the previous example:
<code>$"myTimeSpan:hh\:mm\:ss"}"; //示例输出 15:36:15</code>
Custom TimeSpan format string does not contain placeholder delimiter symbols. Instead, you must specify them explicitly in the format string, as in the example above.
The above is the detailed content of How Can I Custom Format a TimeSpan Object in .NET Using String.Format?. For more information, please follow other related articles on the PHP Chinese website!