Using custom formatting TimeSpan in .NET
Question:
How to format a TimeSpan object into a string using a custom format?
.NET 4.0 and above
.NET 4.0 introduces custom TimeSpan format strings that allow you to specify the desired format using format specifiers. A complete list of available specifiers can be found on the MSDN Custom TimeSpan Format Strings page.
The following is an example of using a custom format string:
<code class="language-csharp">TimeSpan myTimeSpan = TimeSpan.FromMinutes(936); string formattedTimeSpan = string.Format("{0:hh\:mm\:ss}", myTimeSpan); // 输出: "15:36:15"</code>
You can also use C# 6 string interpolation for a more concise representation:
<code class="language-csharp">$"{(myTimeSpan:hh\:mm\:ss)}"; // 输出: "15:36:15"</code>
Escape characters
Please note that the colon ":" character must be escaped with a backslash "". This ensures that it is treated as part of the format string and not as a separator between time components.
MSDN excerpt:
The custom TimeSpan format specifier does not contain placeholder delimiter symbols, such as those that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included as string literals in the custom format string.
The above is the detailed content of How to Customize TimeSpan Formatting in .NET?. For more information, please follow other related articles on the PHP Chinese website!