C# Online Compiler
Example: Calculate the Difference Between Two Time Periods
C
C++
C#
Java
Python
PHP
main.cs
STDIN
Run
// 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
Clear
ADVERTISEMENTS