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#
For .NET 3.5 and lower you could use:
Code taken from a Jon Skeet answer on bytes
For .NET 4.0 and above, see DoctaJonez answer.
Here is my extension method:
Example call:
Output:
This is awesome one:
I would go with
I used the code below. It is long, but still it is one expression, and produces very friendly output, as it does not outputs days, hours, minutes, or seconds if they have value of zero.
In the sample it produces output: "4 days 1 hour 3 seconds".
I use this method. I'm Belgian and speak dutch so plural of hours and minutes is not just adding 's' to the end but almost a different word than singular.
It may seem long but it is very readable I think: