Home »
.Net »
C# Programs
C# - Add Two Times
Learn, how to find the sum of two specified times using TimeSpan in C#?
Submitted by Nidhi, on October 03, 2020 [Last updated : March 19, 2023]
Here, we will find the sum of two specified times using TimeSpan class and store the result into the object of TimeSpan class and print the values of the hour, minute, and seconds using TimeSpan class.
C# program to find the sum of two specified times using TimeSpan
The source code to find the sum of two specified times using the TimeSpan class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# - Add Two Times.
using System;
class Demo
{
static void Main()
{
TimeSpan time;
TimeSpan ts1 = new TimeSpan(10, 20, 50);
TimeSpan ts2 = new TimeSpan(8, 19, 32);
time = ts1 + ts2;
Console.WriteLine("Hours:{0}, Minutes:{1}, Seconds:{2}",time.Hours,time.Minutes,time.Seconds);
}
}
Output
Hours:18, Minutes:40, Seconds:22
Press any key to continue . . .
Explanation
Here, we created a class Demo that contains the Main() method. In the Main() method, we created the two time-spans with a specified time.
time = ts1 + ts2;
Using the above statement, we calculated the sum with two time-span and then we printed the result on the console screen.
C# Date Time Programs »