TimeSpan.Subtract(TimeSpan) Method

Definition

Returns a new TimeSpan object whose value is the difference between the specified TimeSpan object and this instance.

C#
public TimeSpan Subtract(TimeSpan ts);

Parameters

ts
TimeSpan

The time interval to be subtracted.

Returns

A new time interval whose value is the result of the value of this instance minus the value of ts.

Exceptions

The return value is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue.

Examples

The following example uses the Subtract method to calculate the difference between a single TimeSpan value and each of the time intervals in an array. Note that, because TimeSpan format strings do not include negative signs in the result string, the example uses conditional logic to include a negative sign with negative time intervals.

C#
TimeSpan baseTimeSpan = new TimeSpan(1, 12, 15, 16);

// Create an array of timespan intervals.
TimeSpan[] intervals = { 
   TimeSpan.FromDays(1.5), 
   TimeSpan.FromHours(1.5), 
   TimeSpan.FromMinutes(45), 
   TimeSpan.FromMilliseconds(505),
   new TimeSpan(1, 17, 32, 20), 
   new TimeSpan(-8, 30, 0) 
};

// Calculate a new time interval by adding each element to the base interval.
foreach (var interval in intervals)
   Console.WriteLine(@"{0,-10:g} - {3}{1,15:%d\:hh\:mm\:ss\.ffff} = {4}{2:%d\:hh\:mm\:ss\.ffff}",
                     baseTimeSpan, interval, baseTimeSpan.Subtract(interval),
                     interval < TimeSpan.Zero ? "-" : "",
                     baseTimeSpan < interval.Duration() ? "-" : "");

// The example displays the following output:
//       1:12:15:16 - 1:12:00:00.0000 = 0:00:15:16.0000
//       1:12:15:16 - 0:01:30:00.0000 = 1:10:45:16.0000
//       1:12:15:16 - 0:00:45:00.0000 = 1:11:30:16.0000
//       1:12:15:16 - 0:00:00:00.5050 = 1:12:15:15.4950
//       1:12:15:16 - 1:17:32:20.0000 = -0:05:17:04.0000
//       1:12:15:16 - -0:07:30:00.0000 = 1:19:45:16.0000

Remarks

The return value must be between TimeSpan.MinValue and TimeSpan.MaxValue; otherwise, an exception is thrown.

The return value is a new TimeSpan; the original TimeSpan is not modified.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also