Calculating the Difference Between Two Time Periods in C#
In various C# applications—like logging systems, reports, or event planning—measuring the time gap between two events is essential.
Thankfully, the .NET framework provides a simple way to work with time using DateTime
and TimeSpan
structures.
This tutorial continues the concept introduced in our C language lead article, but re-implements the solution using C#’s built-in time handling features.
Namespaces Required
C# provides everything needed for time operations in the default System
namespace, so no additional packages are necessary.
C# Program: Calculate the Difference Between Two Time Periods
// DIFFERENCE BETWEEN TWO TIME PERIODS in C# using DateTime and TimeSpan
using System;
public class W3CW
{
public static void Main()
{
// Step-1 Define two DateTime instances
DateTime startTime = new DateTime(2025, 5, 1, 10, 30, 0);
DateTime endTime = new DateTime(2025, 5, 9, 15, 45, 0);
// Step-2 Calculate the time difference using TimeSpan
TimeSpan difference = endTime - startTime;
// Step-3 Extract hours, minutes, and seconds
int totalHours = (int)difference.TotalHours;
int minutes = difference.Minutes;
int seconds = difference.Seconds;
// Step-4 Display the result
Console.WriteLine("\nTIME DIFFERENCE: {0} HOURS, {1} MINUTES, {2} SECONDS", totalHours, minutes, seconds);
}
}
Output
TIME DIFFERENCE: 205 HOURS, 15 MINUTES, 0 SECONDS
Explanation
Here's how the logic works:
-
Two
DateTime
variables represent the starting and ending timestamps. -
The subtraction of one
DateTime
from another yields aTimeSpan
, which holds the duration. -
From the
TimeSpan
, we extract hours, minutes, and seconds for display.
This method is clean, accurate, and ideal for projects where time tracking or analysis is needed in C# applications.