此方法用于获取新的TimeSpan对象,该对象的值是指定的TimeSpan对象与该实例的差。
Syntax: public TimeSpan Subtract (TimeSpan t);
Parameter:
t: This parameter specifies the time interval to be subtracted.
Return Value: It returns a new TimeSpan object whose value is the difference current instance and the value of t.
Exception: This method will give OverflowException when the resulting TimeSpan is smaller than smallest possible value or greater than the largest possible value.
下面的程序说明了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