Home > Backend Development > C++ > How to Customize TimeSpan Formatting in .NET?

How to Customize TimeSpan Formatting in .NET?

Barbara Streisand
Release: 2025-01-23 13:42:14
Original
887 people have browsed it

How to Customize TimeSpan Formatting in .NET?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template