简体   繁体   中英

How to add two sets of time? e.g 00:10:10 + 00:00:20 = 00:10:30

The following code is how to get the difference between two sets of time . . .But How about Addition? Please help . . .

private void button1_Click(object sender, EventArgs e)
    {
        DateTime dFrom;
        DateTime dTo;
        string sDateFrom = "00:10:38";
        string sDateTo = "00:00:04";
        if (DateTime.TryParse(sDateFrom, out dFrom) && DateTime.TryParse(sDateTo, out dTo))
        {
            TimeSpan TS = dFrom - dTo;
            int hour = TS.Hours;
            int mins = TS.Minutes;
            int secs = TS.Seconds;
  string timeDiff = hour.ToString("00") + ":" + mins.ToString("00") + ":" +  secs.ToString("00");
            textBox1.Text = timeDiff;
        }

    }

It seems like TimeSpans would be better suited here:

TimeSpan tsFrom;
TimeSpan tsTo;

string sFrom = "00:10:38";
string sTo = "00:00:04";

if (TimeSpan.TryParse(sFrom, out tsFrom) && TimeSpan.TryParse(sTo, out tsTo))
{
    TimeSpan ts = tsFrom + tsTo; // 00:10:42
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM