Home »
.Net »
C# Programs
C# - Difference of Two Times
Learn, how to find the difference 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 difference 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 difference of two specified times
The source code to find the difference of two specified times using the TimeSpan class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# - Difference of 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:2, Minutes:1, Seconds:18
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 difference with two time-span and then we printed the result on the console screen.
C# Date Time Programs »