qui qui - 3 years ago 181
C# Question

Timespan formatting

How do you elegantly format a timespan to say example "1 hour 10 minutes" when you have declared it as :

TimeSpan t = new TimeSpan(0, 70, 0);


I am of course aware that you could do some simple maths for this, but I was kinda hoping that there is something in .NET to handle this for me - for more complicated scenarios

Duplicate of How can I String.Format a TimeSpan object with a custom format in .NET?

Answer Source

There is no built-in functionality for this, you'll need to use a custom method, something like:

TimeSpan ts = new TimeSpan(0, 70, 0);
String.Format("{0} hour{1} {2} minute{3}", 
              ts.Hours == 1 ? "" : "s",
              ts.Minutes == 1 ? "" : "s")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download