Mark
Mark

Reputation: 70030

Getting the total hours in a TimeSpan

How can I subtract two dates and get the total hours of the TimeSpan object that is returned?

For example, if the TimeSpan is 2 days, the total hours are 48.

Upvotes: 4

Views: 15974

Answers (2)

ALHr
ALHr

Reputation: 11

I did it this way:

int day = Tempo.Days;
int Hours = Tempo.Hours;
if (day > 0)
{
  for (int i = 0; i < day; i++)
  {
    Hours += 24;
  }
}
string minuto = (Tempo.Minutes < 9) ? "0" + Tempo.Minutes.ToString() : Tempo.Minutes.ToString();
string segundos = (Tempo.Seconds < 9) ? "0" + Tempo.Seconds.ToString() : Tempo.Seconds.ToString();
string texto = Hours.ToString() + ":" + minuto + ":" + segundos;

Upvotes: 0

Dan Tao
Dan Tao

Reputation: 128447

Then you want the TotalHours property of the TimeSpan object:

DateTime today = DateTime.Today;
DateTime twoDaysAgo = today.AddDays(-2.0);

// returns 48.0
double totalHours = (today - twoDaysAgo).TotalHours;

Upvotes: 9

Related Questions