Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timespan formatting [duplicate]

Tags:

c#

.net

timespan

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?

like image 569
Chris James Avatar asked May 08 '09 14:05

Chris James


People also ask

What is data type TimeSpan?

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.

What is TimeSpan value?

A TimeSpan value represents a time interval and can be expressed as a particular number of days, hours, minutes, seconds, and milliseconds.


2 Answers

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") 
like image 63
John Rasch Avatar answered Oct 05 '22 09:10

John Rasch


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"; } 
like image 37
Chris Doggett Avatar answered Oct 05 '22 09:10

Chris Doggett