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#
All literal characters must be escaped.
One way is to create a
DateTime
object and use it for formatting:This is the way I know. I hope someone can suggest a better way.
Personally, I like this approach:
You can make this as custom as you like with no problems:
Here is my version. It shows only as much as necessary, handles pluralization, negatives, and I tried to make it lightweight.
Output Examples
Code
It works for Framework 4
http://msdn.microsoft.com/en-us/library/ee372287.aspx
This is the approach I used my self with conditional formatting. and I post it here because I think this is clean way.
example of outputs:
The formatting is easy.
time.Days:#0:;;\\
the format before;;
is for when value is positive. negative values are ignored. and for zero values we have;;\\
in order to hide it in formatted string. note that the escaped backslash is necessary otherwise it will not format correctly.