0

i have two times in the format.."hours:mins:secs" and and I want to add these two times..how can I do that in C#.....for example...i have two different times like...."2:10:15" and "1:10:55"...the result should be "3:21:10"..can anyone tell me how to do this???

4
  • 2
    What does this have to do with Excel? Commented Feb 26, 2011 at 8:47
  • those two timings in excel... Commented Feb 26, 2011 at 8:56
  • I want to add two time by c#.nte coding and pass it to excel.. Commented Feb 26, 2011 at 8:57
  • You need to describe the problem more clearly. How is this in any way related to Excel? "pass it to excel" is far too simple a description. Commented Feb 26, 2011 at 9:30

3 Answers 3

1

This should do it, like Dean suggested:

 var t1 = TimeSpan.Parse("2:10:15");
 var t2 = TimeSpan.Parse("1:10:55");
 var result = t1 + t2;
Sign up to request clarification or add additional context in comments.

3 Comments

var t1 = TimeSpan.Parse("9:37:00"); var t2 = TimeSpan.Parse("23:59:59"); var result = t1 + t2;result comes as "1.09:36:59".But I need Hours Wise Like "33:96:59"
Then you need to handle that yourself.
Yep, like Lasse writes, I guess you will need to handle it yourself then, sort of like: 'var t1 = TimeSpan.Parse("9:37:00"); var t2 = TimeSpan.Parse("23:59:59"); var hours = t1.Hours + t2.Hours; var minutes = t1.Minutes + t2.Minutes; var seconds = t1.Seconds + t2.Seconds; var result = hours + ":" + minutes + ":" + seconds;'. But also, you may want to handle days, months, years etc. Btw, I guess you meant 32:96:59, not 33:96:59?
0

You'll want to declare two timespan variables plugging in the values above. This will allow you to then add the two time together

Comments

0

While I don't know about datetime conversions between Excel and .Net data types, from looking at your question I wonder if you understand Excel's time values vs the formats. If you're returning a string "2:10:15" then you can just parse it to a datetime value. But if you're reading that number from a cell then the actual value is a floating point number, for example 0.0876 - the value to the right of the decimal being the fraction of the day since midnight. So you should just be able to assign the values from Excel to double variables and perform straight math on them, taking care to handle times that are on separate days.

Sorry I can't be more explicit but I'm just posting from my ipad so can't really give you an example.

Comments

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.