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?
TimeSpan (amount of time) is a new data type that can be used to store information about an elapsed time period or a time span. For example, the value in the picture (148:05:36.254) consists of 148 hours, 5 minutes, 36 seconds, and 254 milliseconds.
A TimeSpan value represents a time interval and can be expressed as a particular number of days, hours, minutes, seconds, and milliseconds.
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,                ts.Hours == 1 ? "" : "s",               ts.Minutes,                ts.Minutes == 1 ? "" : "s") 
                        public static string Pluralize(int n, string unit) {     if (string.IsNullOrEmpty(unit)) return string.Empty;      n = Math.Abs(n); // -1 should be singular, too      return unit + (n == 1 ? string.Empty : "s"); }  public static string TimeSpanInWords(TimeSpan aTimeSpan) {     List<string> timeStrings = new List<string>();      int[] timeParts = new[] { aTimeSpan.Days, aTimeSpan.Hours, aTimeSpan.Minutes, aTimeSpan.Seconds };     string[] timeUnits = new[] { "day", "hour", "minute", "second" };      for (int i = 0; i < timeParts.Length; i++)     {         if (timeParts[i] > 0)         {             timeStrings.Add(string.Format("{0} {1}", timeParts[i], Pluralize(timeParts[i], timeUnits[i])));         }     }      return timeStrings.Count != 0 ? string.Join(", ", timeStrings.ToArray()) : "0 seconds"; } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With