What is the recommended way of formatting TimeSpan
objects into a string with a custom format?
相关问题
- Generic Generics in Managed C++
- how to split a list into a given number of sub-lis
- How to Debug/Register a Permanent WMI Event Which
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
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:
(UPDATE) and here is an example using C# 6 string interpolation:
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:
If you want the duration format similar to youtube, given the number of seconds
Output:
You can also go with:
EDIT:
You can also look at Strings.Format.
This is a pain in VS 2010, here's my workaround solution.
I wanted to return a string such as "1 day 2 hours 3 minutes" and also take into account if for example days or minuttes are 0 and then not showing them. thanks to John Rasch for his answer which mine is barely an extension of
Simple. Use
TimeSpan.ToString
with c, g or G. More information at http://msdn.microsoft.com/en-us/library/ee372286.aspx