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

📅  最后修改于: 2021-05-29 23:06:42             🧑  作者: Mango

此方法用于获取表示指定秒数的TimeSpan,精确到最接近的毫秒。

例外情况:

  • OverflowException:当给定的double值小于最小可能值或大于最大可能值,或者该值是PositiveInfinity或NegativeInfinity。
  • ArgumentException:当值为NaN时。

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

范例1:

// C# program to demonstrate the
// TimeSpan.FromSeconds(Double)
// Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            TimeSpan interval = TimeSpan.FromSeconds(0.43459);
            Console.WriteLine("The Timespan is : {0}",
                                           interval);
        }
  
        catch (OverflowException e) {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
The Timespan is : 00:00:00.4350000

示例2:对于溢出异常

// C# program to demonstrate the
// TimeSpan.FromSeconds(Double) 
// Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            TimeSpan interval = 
             TimeSpan.FromSeconds(Double.NegativeInfinity);
  
            Console.WriteLine("The Timespan is : {0}",
                                           interval);
        }
  
        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.fromseconds?view=netframework-4.7.2