TimeSpan.Subtract(TimeSpan) TimeSpan.Subtract(TimeSpan) TimeSpan.Subtract(TimeSpan) TimeSpan.Subtract(TimeSpan) Method

定义

返回一个新的 TimeSpan 对象,其值为指定的 TimeSpan 对象与此实例的值之差。Returns a new TimeSpan object whose value is the difference between the specified TimeSpan object and this instance.

public:
 TimeSpan Subtract(TimeSpan ts);
public TimeSpan Subtract (TimeSpan ts);
member this.Subtract : TimeSpan -> TimeSpan
Public Function Subtract (ts As TimeSpan) As TimeSpan

参数

ts
TimeSpan TimeSpan TimeSpan TimeSpan

要减去的时间间隔。The time interval to be subtracted.

返回

一个新的时间间隔,其值为此实例的值减去 ts 的值所得的结果。A new time interval whose value is the result of the value of this instance minus the value of ts.

异常

返回值小于 MinValue 或大于 MaxValueThe return value is less than MinValue or greater than MaxValue.

示例

下面的示例使用Subtract方法来计算数组中单个TimeSpan值和每个时间间隔之间的差异。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. 请注意, 由于TimeSpan格式字符串不会在结果字符串中包含负号, 因此该示例使用条件逻辑来包括负号, 并带有负的时间间隔。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.

using System;

public class Example
{
   public static void Main()
   {
      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

注解

返回值必须介于和TimeSpan.MinValue TimeSpan.MaxValue之间; 否则, 将引发异常。The return value must be between TimeSpan.MinValue and TimeSpan.MaxValue; otherwise, an exception is thrown.

返回值为新TimeSpan的; 不会修改原始TimeSpan值。The return value is a new TimeSpan; the original TimeSpan is not modified.

适用于

另请参阅