razi3lCast
razi3lCast

Reputation: 115

TimeSpan Showing only Hours?

I have this problem in my MVC Application.

I have TimeSpan which contains for example 2 days 15 hours 31 minutes and 34 seconds.

I want to show only the hours/minutes/seconds and the thing is that I want to add the days to the hours like 63:31:34 .I tried to add a new time span like time.Add(new TimeSpan(time.Days * 24, 0, 0),but the .NET add that like 2 days.

Can you help me to solve my problem?

Upvotes: 3

Views: 2235

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98868

Hours property can't be 63 since it's range from -23 through 23. You can get this 63:31:34 as a textual representation only using TimeSpan properties.

var ts = new TimeSpan(2, 15, 31, 34);
Console.WriteLine("{0}:{1}:{2}", (int)ts.TotalHours, ts.Minutes, ts.Seconds);

Prints;

63:31:34

As Jeppe mentioned -not in your case- ts.TotalHours part can be limitted double precision since it's calculated as (double)_ticks * HoursPerTick based on the instance. In such a case, using ts.Ticks / TimeSpan.TicksPerHour can be better way to produce long / long operation.

Upvotes: 1

Gustav
Gustav

Reputation: 56026

Adding to Jeppes note, a method avoiding double could be to actively use the day count:

TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750); 
Console.WriteLine("{0}:{1}:{2}", interval.Days * 24 + interval.Hours, interval.Minutes, interval.Seconds);

// result: 39:42:45

Upvotes: 1

marcinax
marcinax

Reputation: 1195

After adding days use TimeSpan.TotalHours to display the time:

For example:

TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750); 
Console.WriteLine("{0}:{1}:{2}", interval.TotalHours, interval.Minutes, interval.Seconds);

Upvotes: 0

Related Questions