Robert Mazurowski
Robert Mazurowski

Reputation: 337

How to display Hours and Minutes from timespan with more than 24 hours

My timespan is for example:

Timespan span = new Timespan(40,24,34);

And I have this line

FormClock.Text = TimeToInstall.ToString(@"hh\:mm\:ss");

I want to display this in the Text like this:

40:24:34

How to do this?

Upvotes: 1

Views: 7779

Answers (1)

NikolaiDante
NikolaiDante

Reputation: 18639

Looking at MSDN, you can't do it with a standard .ToString() format. The TotalHours property of a timespan seems to be what you need to get from days to hours.

From MSDN:

TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750); Console.WriteLine("Value of TimeSpan: {0}", interval);

  Console.WriteLine("{0:N5} hours, as follows:", interval.TotalHours);
  Console.WriteLine("   Hours:        {0,3}", 
                    interval.Days * 24 + interval.Hours);
  Console.WriteLine("   Minutes:      {0,3}", interval.Minutes);
  Console.WriteLine("   Seconds:      {0,3}", interval.Seconds);
  Console.WriteLine("   Milliseconds: {0,3}", interval.Milliseconds);

So in your case:

FormClock.Text = string.Format("{0}:{1}:{2}". TimeToInstall.Days * 24 + TimeToInstall.Hours, TimeToInstall.Minutes, TimeToInstall.Seconds); 

If it's something you're going to use a lot you could look at rolling it into some sort of extension method.

Upvotes: 5

Related Questions