.NET developers often require precise control over how TimeSpan
objects are displayed. This guide details techniques for creating custom string representations of TimeSpan
values.
.NET 4.0 introduced robust custom formatting for TimeSpan
objects. The String.Format()
method, combined with custom format strings, offers extensive control.
Example:
<code class="language-csharp">string formattedTimeSpan = string.Format("{0:hh\:mm\:ss}", myTimeSpan); // Output: 15:36:15</code>
C# 6's string interpolation provides a more concise alternative:
<code class="language-csharp">string formattedTimeSpan = $"{myTimeSpan:hh\:mm\:ss}"; // Output: 15:36:15</code>
Characters like ":" and "." have special meanings in format strings and need escaping using a backslash ("").
Example:
<code class="language-csharp">string formattedTimeSpan = string.Format("{0:dd\.hh\:mm}", myTimeSpan); // Output: 2.15:36</code>
Here, the period and colon are treated literally as separators.
Microsoft's documentation on Custom TimeSpan Format Strings provides a complete list of available specifiers. These range from common units like "hh" (hours) to more granular options such as "ff" (microseconds), allowing for highly customized output. Referencing this documentation is key to achieving precise formatting.
The above is the detailed content of How Can I Format TimeSpan Objects with Custom Formats in .NET?. For more information, please follow other related articles on the PHP Chinese website!