-1

How can i put the 2 times together And i want it to stay in the time format: hh:mm:ss

string time1 = "00:49:35";
string time2 = "00:31:34";

totaltime = time1 + time2;

This should be the result 01:21:09 (1 hour and 21 min and 09 sec)

5
  • What is your desired output? Commented Jan 28, 2016 at 10:44
  • How about doing a SO search first? Like e.g. "Adding two DateTime objects together". Commented Jan 28, 2016 at 10:45
  • 3
    You're confusing data with representation. If your input is a string, you need to parse it to a sensible format (e.g. TimeSpan), then add those, and then print the timespan in the representation you want. Commented Jan 28, 2016 at 10:45
  • 2
    Checkout DateTime or TimeSpan there are thousands of such questions in SO Commented Jan 28, 2016 at 10:45
  • the 2 times together 01:21:09 (1 hour and 21 min and 09 sec) Commented Jan 28, 2016 at 10:47

2 Answers 2

4

How about using the TimeSpan class:

TimeSpan time1 = TimeSpan.Parse("00:49:35");
TimeSpan time2 = TimeSpan.Parse("00:31:34");

TimeSpan res = time1 + time2;

Console.WriteLine(res.ToString()); // 01:21:09, you may omit the ToString() call

If you don't want to Parse a string, you can construct a TimeSpan object:

TimeSpan time1 = new TimeSpan(00, 49 ,35);
TimeSpan time2 = new TimeSpan(00, 31 ,34);
TimeSpan res = time1 + time2;
Console.WriteLine(res); // 01:21:09
Sign up to request clarification or add additional context in comments.

Comments

2

This works for me:

(TimeSpan.Parse(time1) + TimeSpan.Parse(time2)).ToString()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.