0

Hi I have to execute a sum of hours, to do so I use the code c # below: first convert hourtot into timespan then I execute the total sum, at the end the total I get 08:30 which is impossible, how can I solve this? and what is it due to?

C# Code:

    /*
    hourtot values:
    08:30
    10:00
    09:00
    08:30
    10:00
    10:30*/

TimeSpan tot= TimeSpan.Zero;
 foreach (DataRow dr in dt.Rows)
 {
    String hourtot= r.CaricaOreGiornaliere(dr["date"].ToString());
    if(hourtot.Equals("00:00") == false)
    {
      TimeSpan hourcant= TimeSpan.Parse(hourtot.ToString());
      tot= tot+ hourcant;
    }
    }
   labelris.text = "" + tot.ToString(@"hh\:mm"); //this print 08:30
riki
  • 1,502
  • 5
  • 17
  • 45

1 Answers1

5

The problem is in your tot.ToString(@"hh\:mm"); line.

When you use hh and mm, it uses Hours and Minutes values of your TimeSpan object, not TotalHours and TotalMinutes which is what you want.

So, if your total is more than one day in terms of hours, it will take the first 24 hours as a day. For example, if your total is 27 hours, then your TimeSpan.Days will be 1, and TimeSpan.Hours will be 3.

Here's the exact same program of yours but written as a simple Console program.

static void Main(string[] args)
{
    List<string> times = new List<string>();
    times.Add("08:30");
    times.Add("10:00");
    times.Add("09:00");

    TimeSpan tot = TimeSpan.Zero;
    foreach (var time in times)
    {
        if (time.Equals("00:00") == false)
        {
            TimeSpan hourcant = TimeSpan.Parse(time);
            tot = tot + hourcant;
        }
    }

    Console.WriteLine(tot.ToString(@"hh\:mm"));

    Console.ReadLine();
}

And the output is

03:30

However, looks at the values of tot inside the debugger.

enter image description here

So your method is fine you need to print it better. Something like this:

Console.WriteLine("Total Hours = {0}", tot.TotalHours);

EDIT:

Using Matthew Watson's suggestion below will give the output in the exact format you want.

Console.WriteLine(tot.ToString(@"d\.hh\:mm"));
Sach
  • 10,091
  • 8
  • 47
  • 84