Skip to content
Related Articles

Related Articles

TimeSpan.FromHours() Method in C#

Improve Article
Save Article
Like Article
  • Last Updated : 30 Sep, 2019

This method is used to get a TimeSpan that represents a specified number of hours, accurate to the nearest millisecond.

Syntax: public static TimeSpan FromHours (double value);

Parameter:
value: This parameter specifies the number of hours, accurate to the nearest millisecond.

Return Value: It returns a new TimeSpan object that represents the value.

Exceptions:

  • OverflowException: It occurs when the given double value is smaller than the smallest possible value or greater than the largest possible value or the value is PositiveInfinity or is NegativeInfinity.
  • ArgumentException: If the value is equal to NaN.

Below programs illustrate the use of TimeSpan.FromHours(Double) Method:

Program 1:




// C# program to demonstrate the
// TimeSpan.FromDays(Double) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            TimeSpan interval = TimeSpan.FromHours(12.3459);
            Console.WriteLine("The Timespan is : {0}",
                                            interval);
        }
  
        catch (OverflowException e) {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
Output:
The Timespan is : 12:20:45.2400000

Program 2: For Overflow Exception




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

Reference:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!