1

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.

3
  • 1
    I don't have access to the rest of your code, but I don't think you can do math with string's. Do not cast time to string. Commented Jan 3, 2022 at 13:51
  • 1
    What exactly do you think the sum of a set of DateTimes would represent? Commented Jan 3, 2022 at 13:52
  • 1
    Also, have a look at this learn.microsoft.com/en-us/dotnet/api/… Commented Jan 3, 2022 at 13:55

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Seems a better answer for explaining why the .Add method need a TimeSpan type and adding the string type.
3

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

2 Comments

The OP says: I want to total up the time so what is the result of your code if instead of 40 minutes you add 5 hours and 30 minutes?
My output is 19:10:00 as I wrote in comment code. If sum that you said the result will be 00:00:00. You can run it here. dotnetfiddle.net/gOiVXX

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.