-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)

Ofiris
  • 6,047
  • 6
  • 35
  • 58
CaMeX
  • 89
  • 10
  • What is your desired output? – Uwe Keim Jan 28 '16 at 10:44
  • How about doing a SO search first? Like e.g. "[Adding two DateTime objects together](http://stackoverflow.com/questions/28067247/adding-two-datetime-objects-together)". – Uwe Keim Jan 28 '16 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. – CodeCaster Jan 28 '16 at 10:45
  • 2
    Checkout `DateTime` or `TimeSpan` there are thousands of such questions in SO – Ian Jan 28 '16 at 10:45
  • the 2 times together 01:21:09 (1 hour and 21 min and 09 sec) – CaMeX Jan 28 '16 at 10:47

2 Answers2

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
Ofiris
  • 6,047
  • 6
  • 35
  • 58
2

This works for me:

(TimeSpan.Parse(time1) + TimeSpan.Parse(time2)).ToString()
NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61