Timespan.Subtract() Method In C#

In C#, the TimeSpan.Subtract function belongs to the TimeSpan structure and is employed to deduct one TimeSpan from another. This function generates a fresh TimeSpan object that reflects the outcome of the subtraction.

Purpose:

The main function of TimeSpan.Subtract is to calculate the variance between two time spans. This method empowers programmers to perform arithmetic operations on time intervals and generate a fresh TimeSpan object that reflects the outcome of the subtraction.

Syntax:

It has the following syntax:

Example

public TimeSpan Subtract(TimeSpan ts);

Parameters

  • ts: This TimeSpan parameter signifies the specific duration that will be removed from the existing TimeSpan object.
  • Return Value

The function yields a fresh TimeSpan object that signifies the outcome of deducting the specified TimeSpan (ts) from the present instance.

Behaviour

The initial values utilized in the operation remain unchanged by the Subtract function; instead, a fresh TimeSpan instance is generated and returned.

A negative TimeSpan will be generated when the time span represented by 'ts' surpasses the duration of the current instance.

The resulting TimeSpan has the ability to signify durations that are either positive or negative, based on the sequence in which the subtraction operation is performed.

Use Cases

  • Calculating the duration between two points in time.
  • Handling scenarios requires finding the time difference between two DateTime instances.
  • Time-based arithmetic, such as determining intervals for scheduling or tracking elapsed time.
  • Considerations

  • The result may be negative if the TimeSpan being subtracted is greater than the original TimeSpan.
  • The Subtract method is useful in various scenarios involving time calculations, making it a fundamental part of time manipulation in C#.
  • Example:

Let's consider an example to demonstrate the utilization of the Timespan.Subtract method in C#.

Example

using System;
class Program
{
    static void Main()
    {
        // Creating two TimeSpan instances
        TimeSpan time_Span1 = new TimeSpan(6, 35, 12);  // 6 hours and 35 minutes
        TimeSpan time_Span2 = new TimeSpan(8, 40, 18);  // 8 hour and 40 minutes
        // Using Subtract() method to find the difference between timeSpan1 and timeSpan2
        TimeSpan result = time_Span1.Subtract(time_Span2);
        // Displaying the original TimeSpans and the result
        Console.WriteLine("Original TimeSpan 1: " + time_Span1);
        Console.WriteLine("TimeSpan 2 to subtract: " + time_Span2);
        Console.WriteLine("Result after subtraction: " + result);
    }
}

Output:

Output

Original TimeSpan 1: 06:35:12
TimeSpan 2 to subtract: 08:40:18
Result after subtraction: -02:05:06

Generating TimeSpan Objects

The TimeSpan constructor generates two separate TimeSpan objects, timeSpan1 and timeSpan2.

Time_Span1 denotes a duration of 6 hours, 35 minutes, and 12 seconds.

The time interval of 8 hours, 40 minutes, and 18 seconds is denoted by the time_Span2 variable.

  1. Minus Operation

The disparity between timeSpan1 and timeSpan2 can be determined by employing the Subtract method.

The result is stored in the 'result' variable.

The Subtract method generates a fresh TimeSpan object that signifies the outcome of the subtraction, without altering the original TimeSpan objects.

  1. Presentation of Results

The Console displays the initial TimeSpan values (timeSpan1 and timeSpan2) along with the resulting subtracted value, which is then output using WriteLine.

The software displays the initial time intervals and the outcome of the deduction on the Console.

Exception

This function may raise an OverflowException if the TimeSpan produced is below the minimum allowable value or exceeds the maximum allowable value.

Example:

Let's consider a scenario to demonstrate the application of the Timespan.Subtract method along with exception handling in C#.

Example

using System; 
class Demo
{ 
    public static void Main() 
    { 
        //main method
        try 
        { 
            // the TimeSpan object 
            TimeSpan t1 = TimeSpan.MinValue; 
            TimeSpan t2 = new TimeSpan(4, 23, 46, 28); 
            TimeSpan vari_able = t1.Subtract(t2); 
            Console.WriteLine("The Timespan is : {0}", vari_able); 
        } 
        catch (OverflowException e)  
        { 
            Console.Write("Exception Thrown: "); 
            Console.Write("{0}", e.GetType(), e.Message); 
        } 
    } 
}

Output:

Output

Exception Thrown: System.OverflowException

Explanation:

  1. Using Directives

The using System; statement imports the System namespace, which comprises essential classes and fundamental types.

  1. Declaring a Class

The Demo class has been defined. Within this class, the Main function acts as the starting point for the application.

  1. Attempt Block

The code within the try block attempts to execute a certain task, while the catch block is responsible for managing any exceptions that might occur.

  1. TimeSpan Objects

T1 and T2 are the identifiers for the two TimeSpan instances that have been initialized.

With TimeSpan, t1 is instantiated. MinValue denotes the smallest value that TimeSpan can have.

The specific duration set for t2 is 4 days, 23 hours, 46 minutes, and 28 seconds.

  1. Performing Subtraction

When 't2' is passed as an argument, the Subtract function is invoked on the 't1' TimeSpan instance, and the outcome is saved in the 'vari_able' variable.

  1. Printed Output

Utilizing the Console, the application displays the subtraction outcome using Console.WriteLine.

  1. Exception Handling (OverflowException)

The catch block is designed to handle an OverflowException that may occur during program execution, such as when the result of a subtraction operation exceeds the permissible range for TimeSpan.

Afterwards, the software displays details regarding the exception, such as its category and the accompanying message.

  1. Sample Console Output

The software displays the TimeSpan outcome on the Console without any errors. The variable's value is shown utilizing the format specifier {0}.

Conclusion:

In summary, this program showcases the utilization of the TimeSpan class in C# to subtract two instances of TimeSpan while managing potential overflow exceptions that could arise. The illustration presented with TimeSpan.MinValue highlights a situation where an overflow may happen as a result of the subtraction.

Input Required

This code uses input(). Please provide values below: