Proper way to calculat time difference in c#

I'm calculating overtime duration of a worker. I've load data into datagridview. I've named column as startot(5th in position) and endot(6th in position). This is my code to calculate duration

 TimeSpan duration = new TimeSpan();
 foreach (DataGridViewRow row in attenViewGrid.Rows)
 {
     string start = row.Cells[5].Value.ToString();
     string end = row.Cells[6].Value.ToString();
     duration += DateTime.Parse(end).Subtract(DateTime.Parse(start));
  }

Now I'm facing problem when overtime start at 10:00 am to nextday 9:00am. What can be the best way to calculate over time duration.

1 answer

  • answered 2018-07-12 07:28 Francesco

    You should specify date and time in your table cell, when you create a datetime object from parsing a time string it sets a fixed date.

    Otherwise you could put a condition for a one-day increment:

     TimeSpan duration = new TimeSpan();
     foreach (DataGridViewRow row in attenViewGrid.Rows)
     {
         string start = row.Cells[5].Value.ToString();
         string end = row.Cells[6].Value.ToString();
    
         if(DateTime.Parse(end).Compare(DateTime.Parse(start)) < 0) 
             duration += Timespan.FromDays(1);
    
         duration += DateTime.Parse(end).Subtract(DateTime.Parse(start));
      }