📜  C#中的TimeSpan.Subtract()方法

📅  最后修改于: 2021-05-29 15:01:16             🧑  作者: Mango

此方法用于获取新的TimeSpan对象,该对象的值是指定的TimeSpan对象与该实例的差。

下面的程序说明了TimeSpan.Subtract(TimeSpan)方法的用法:

范例1:

// C# program to demonstrate the
// TimeSpan.Subtract(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.Subtract(t2);
  
            Console.WriteLine("The Timespan is : {0}",
                                            variable);
        }
  
        catch (OverflowException e) 
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
The Timespan is : 2.11:20:17

示例2:对于溢出异常

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

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.timespan.subtract?view=netframework-4.7.2