Home > Mobile >  DateTime adding up in C#
DateTime adding up in C#

Time:01-04

I have an excel sheet which has time in one of it's columns.

Example:

Name, Time
John  02:32
Peter 14:20
Paul  11:00

I imported my excel to a datagrid view, and I want to total up the time. I don't know how to add up the time.

I did try the DateTime but it doesn't work, maybe I missed something.

Here's what I try.

DateTime peopleTime = new DateTime();

Then I try to loop through the rows and add the time column.

peopleTime.Add(dataGrid.Rows[i].Cell[1].Value.ToString());

It doesn't work.

CodePudding user response:

DateTime represents a point in time, you seem to want a duration, for that there's built in TimeSpan type.

A simple example how to parse and add up an array of string times, could look like this:

https://dotnetfiddle.net/WDkRfo

var stringTimes = new [] { "01:30", "02:30" };
        
var total = new TimeSpan();
foreach(var stringTime in stringTimes) {
    total  = TimeSpan.Parse(stringTime);
}
        
Console.WriteLine(total);

CodePudding user response:

Is this that you want?

DateTime date1 = DateTime.Parse("18:30");
DateTime date2 = DateTime.Parse("00:40:00");
DateTime date3 = date1.Add(date2.TimeOfDay); 
Console.WriteLine(date3.TimeOfDay); // 19:10:00
  •  Tags:  
  • Related