Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to Add Two TimeSpan
The TimeSpan structure in C# represents a time interval and provides methods to perform arithmetic operations. You can add two TimeSpan objects using the Add() method or the + operator to get the combined duration.
Syntax
Following is the syntax for adding two TimeSpan objects using the Add() method −
TimeSpan result = timespan1.Add(timespan2);
You can also use the + operator for addition −
TimeSpan result = timespan1 + timespan2;
Using the Add() Method
The Add() method returns a new TimeSpan that represents the sum of two time intervals −
using System;
public class Demo {
public static void Main() {
TimeSpan t1 = TimeSpan.FromMinutes(1);
TimeSpan t2 = TimeSpan.FromMinutes(2);
Console.WriteLine("First TimeSpan: " + t1);
Console.WriteLine("Second TimeSpan: " + t2);
// Adding using Add() method
TimeSpan res = t1.Add(t2);
Console.WriteLine("Resultant TimeSpan: " + res);
}
}
The output of the above code is −
First TimeSpan: 00:01:00 Second TimeSpan: 00:02:00 Resultant TimeSpan: 00:03:00
Using the + Operator
The + operator provides a more intuitive way to add TimeSpan objects −
using System;
public class Demo {
public static void Main() {
TimeSpan hours = TimeSpan.FromHours(2);
TimeSpan minutes = TimeSpan.FromMinutes(30);
TimeSpan seconds = TimeSpan.FromSeconds(45);
Console.WriteLine("Hours: " + hours);
Console.WriteLine("Minutes: " + minutes);
Console.WriteLine("Seconds: " + seconds);
// Adding using + operator
TimeSpan total = hours + minutes + seconds;
Console.WriteLine("Total Time: " + total);
}
}
The output of the above code is −
Hours: 02:00:00 Minutes: 00:30:00 Seconds: 00:00:45 Total Time: 02:30:45
Adding Different TimeSpan Units
You can create TimeSpan objects from various time units and add them together −
using System;
public class Demo {
public static void Main() {
TimeSpan days = TimeSpan.FromDays(1);
TimeSpan hours = TimeSpan.FromHours(5);
TimeSpan minutes = TimeSpan.FromMinutes(30);
Console.WriteLine("Days: " + days);
Console.WriteLine("Hours: " + hours);
Console.WriteLine("Minutes: " + minutes);
TimeSpan totalTime = days + hours + minutes;
Console.WriteLine("Combined Duration: " + totalTime);
Console.WriteLine("Total Days: " + totalTime.TotalDays);
Console.WriteLine("Total Hours: " + totalTime.TotalHours);
}
}
The output of the above code is −
Days: 1.00:00:00 Hours: 05:00:00 Minutes: 00:30:00 Combined Duration: 1.05:30:00 Total Days: 1.2291666666666667 Total Hours: 29.5
Conclusion
Adding TimeSpan objects in C# can be done using either the Add() method or the + operator. Both approaches return a new TimeSpan representing the combined duration, making it easy to perform time calculations in your applications.
