c# - How can I String.Format a TimeSpan object with a custom format in .NET?

ID : 20391

viewed : 16

Tags : c#.netstringtimeformattingc#

Top 5 Answer for c# - How can I String.Format a TimeSpan object with a custom format in .NET?

vote vote


Please note: this answer is for .Net 4.0 and above. If you want to format a TimeSpan in .Net 3.5 or below please see JohannesH's answer.

Custom TimeSpan format strings were introduced in .Net 4.0. You can find a full reference of available format specifiers at the MSDN Custom TimeSpan Format Strings page.

Here's an example timespan format string:

string.Format("{0:hh\\:mm\\:ss}", myTimeSpan); //example output 15:36:15 

(UPDATE) and here is an example using C# 6 string interpolation:

$"{myTimeSpan:hh\\:mm\\:ss}"; //example output 15:36:15 

You need to escape the ":" character with a "\" (which itself must be escaped unless you're using a verbatim string).

This excerpt from the MSDN Custom TimeSpan Format Strings page explains about escaping the ":" and "." characters in a format string:

The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.

vote vote


For .NET 3.5 and lower you could use:

string.Format ("{0:00}:{1:00}:{2:00}",                 (int)myTimeSpan.TotalHours,                      myTimeSpan.Minutes,                      myTimeSpan.Seconds); 

Code taken from a Jon Skeet answer on bytes

For .NET 4.0 and above, see DoctaJonez answer.

vote vote


One way is to create a DateTime object and use it for formatting:

new DateTime(myTimeSpan.Ticks).ToString(myCustomFormat)  // or using String.Format: String.Format("{0:HHmmss}", new DateTime(myTimeSpan.Ticks)) 

This is the way I know. I hope someone can suggest a better way.

vote vote


Simple. Use TimeSpan.ToString with c, g or G. More information at MSDN

vote vote


I would go with


Top 3 video Explaining c# - How can I String.Format a TimeSpan object with a custom format in .NET?