c-sharp
  1. c-sharp-program-to-calculate-difference-between-two-time-periods

Program to Calculate Difference Between Two Time Periods - (C# Basic Programs)

Calculating the difference between two time periods is a commonly required calculation when working with time in applications. In this tutorial, we will discuss a program to calculate the difference between two time periods using C# programming language.

Syntax

The syntax of the TimeSpan structure that is used to calculate the difference between two time periods is as follows:

TimeSpan duration = startTime - endTime;

Example

using System;

namespace TimeDifference
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the start time (yyyy/mm/dd hh:mm:ss):");
            DateTime startTime = DateTime.Parse(Console.ReadLine());

            Console.WriteLine("Enter the end time (yyyy/mm/dd hh:mm:ss):");
            DateTime endTime = DateTime.Parse(Console.ReadLine());

            TimeSpan duration = startTime - endTime;

            Console.WriteLine("Time difference: " + duration.Duration());

            Console.ReadLine();
        }
    }
}

Output:

Enter the start time (yyyy/mm/dd hh:mm:ss):
2022/09/10 09:30:00
Enter the end time (yyyy/mm/dd hh:mm:ss):
2022/09/10 10:45:30
Time difference: 01:15:30

Explanation

The example program prompts users to enter two dates and times, which are then converted to DateTime objects. By subtracting the start time from the end time, we get a TimeSpan object that represents the difference between the two times. We then use the Duration method to ensure that the time difference is represented as a positive value.

Use

This program can be used in any application that requires calculating the time difference between two points in time. Applications that deal with scheduling or time-tracking may require this functionality.

Summary

In this tutorial, we have discussed a program to calculate the difference between two time periods using C# programming language. We have seen the syntax, example, explanation, use, and how this program can be implemented in various applications. By using this program, developers can efficiently calculate the time difference between two time periods in their applications.

Published on: