TimeSpan.Add() Method in C#

This method is used to a get new TimeSpan object whose value is the sum of the specified TimeSpan object and this instance.

Syntax public TimeSpan Add (TimeSpan t);

Parameter:
t: This parameter specifies the time interval to be added.



Return Value: It returns a new TimeSpan object whose value is the sum current instance and the value of t.

Exception:OverflowException:It occurs when the resulting TimeSpan is smaller than smallest possible value or greater than the largest possible value.

Below programs illustrate the use of TimeSpan.Add(TimeSpan) Method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate the
// TimeSpan.Add(TimeSpan) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // creating the TimeSpan object
            TimeSpan t1 = new TimeSpan(3, 22, 35, 33);
            TimeSpan t2 = new TimeSpan(1, 11, 15, 16);
            TimeSpan variable = t1.Add(t2);
  
            Console.WriteLine("The Timespan is : {0}",
                                            variable);
        }
  
        catch (OverflowException e) 
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}

chevron_right


Output:

The Timespan is : 5:09:50:49

Example 2: For Overflow Exception

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate the
// TimeSpan.Add(TimeSpan) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // the TimeSpan object
            TimeSpan t1 = new TimeSpan(3, 22, 35, 33);
            TimeSpan t2 = TimeSpan.MaxValue;
            TimeSpan variable = t1.Add(t2);
  
            Console.WriteLine("The Timespan is : {0}",
                                            variable);
        }
  
        catch (OverflowException e)
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}

chevron_right


Output:

Exception Thrown: System.OverflowException

Reference:



My Personal Notes arrow_drop_up

Budding Web DeveloperKeen learnerAverage CoderDancer&Social Activist

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : shubham_singh



Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.