TimeSpan.Add() Method in C#


The TimeSpan.Add() method in C# is used to return a new TimeSpan object whose value is the sum of the specified TimeSpan object and this instance.

Syntax

The syntax is as follows −

public TimeSpan Add (TimeSpan span);

Above, the parameter span is the time interval to add.

Example

Let us now see an example −

 Live Demo

using System;
public class Demo {
   public static void Main(){
      TimeSpan span1 = new TimeSpan(2, 17, 20, 30);
      TimeSpan span2 = new TimeSpan(3, 18, 25, 25);
      TimeSpan span3 = new TimeSpan(-8, 30, 0);
      TimeSpan res1 = span1.Add(span2);
      TimeSpan res2 = span2.Add(span3);
      Console.WriteLine("Final Timespan (TimeSpan1 + TimeSpan2) = "+res1);
      Console.WriteLine("Final Timespan (TimeSpan2 + TimeSpan3) = "+res2);
   }
}

Output

This will produce the following output −

Final Timespan (TimeSpan1 + TimeSpan2) = 6.11:45:55
Final Timespan (TimeSpan2 + TimeSpan3) = 3.10:55:25

Example

Let us now see another example −

 Live Demo

using System;
public class Demo {
   public static void Main(){
      TimeSpan span1 = new TimeSpan(-6, 25, 0);
      TimeSpan span2 = new TimeSpan(1, 11, 25, 20);
      TimeSpan span3 = TimeSpan.MinValue;
      TimeSpan res1 = span1.Add(span2);
      TimeSpan res2 = span2.Add(span3);
      Console.WriteLine("Final Timespan (TimeSpan1 + TimeSpan2) = "+res1);
      Console.WriteLine("Final Timespan (TimeSpan2 + TimeSpan3) = "+res2);
   }
}

Output

This will produce the following output −

Final Timespan (TimeSpan1 + TimeSpan2) = 1.05:50:20
Final Timespan (TimeSpan2 + TimeSpan3) = -10675197.15:22:45.4775808
raja
Published on 03-Dec-2019 07:07:02
Advertisements