Home >Backend Development >C++ >How Can I Custom Format a TimeSpan Object in .NET Using String.Format?

How Can I Custom Format a TimeSpan Object in .NET Using String.Format?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-23 13:59:09563browse

How Can I Custom Format a TimeSpan Object in .NET Using String.Format?

Use String.Format to custom format TimeSpan object in .NET

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 format specifier

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.

Example format string

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.

Escape special characters

Please note that the ":" character in the format string must be escaped with "". This is to distinguish it from TimeSpan delimiters.

Using C# 6 string interpolation

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>

Separator

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!

Statement:
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