TimeSpan.FromHours() Method in C#


The TimeSpan.FromHours() method in C# is used to return a TimeSpan that represents a specified number of hours, where the specification is accurate to the nearest millisecond.

Syntax

The syntax is as follows −

public static TimeSpan FromHours (double val);

Above, the value val is a number of hours accurate to the nearest millisecond.

Example

Let us now see an example −

 Live Demo

using System;
public class Demo {
   public static void Main(){
      TimeSpan span1 = TimeSpan.FromDays(0.000323456);
      TimeSpan span2 = new TimeSpan(-2, 05, 10);
      TimeSpan span3 = TimeSpan.FromHours(5);
      Console.WriteLine("TimeSpan1 = "+span1);
      Console.WriteLine("TimeSpan2 = "+span2);
      Console.WriteLine("TimeSpan3 = "+span3);
      Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2));
      Console.WriteLine("Result (Comparison of span2 and span3) = "+TimeSpan.Compare(span2, span3));
   }
}

Output

This will produce the following output −

TimeSpan1 = 00:00:27.9470000
TimeSpan2 = -01:54:50
TimeSpan3 = 05:00:00
Result (Comparison of span1 and span2) = 1
Result (Comparison of span2 and span3) = -1

Example

Let us now see another example −

 Live Demo

using System;
public class Demo {
   public static void Main(){
      TimeSpan span1 = TimeSpan.FromDays(15);
      TimeSpan span2 = new TimeSpan(5, 15, 30);
      TimeSpan span3 = TimeSpan.FromHours(5);
      Console.WriteLine("TimeSpan1 = "+span1);
      Console.WriteLine("TimeSpan2 = "+span2);
      Console.WriteLine("TimeSpan3 = "+span3);
      Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2));
      Console.WriteLine("Result (Comparison of span2 and span3) = "+TimeSpan.Compare(span2, span3));
      Console.WriteLine("Result (Comparison of span1 and span3) = "+TimeSpan.Compare(span1, span3));
   }
}

Output

This will produce the following output −

TimeSpan1 = 15.00:00:00
TimeSpan2 = 05:15:30
TimeSpan3 = 05:00:00
Result (Comparison of span1 and span2) = 1
Result (Comparison of span2 and span3) = 1
Result (Comparison of span1 and span3) = 1
raja
Published on 03-Dec-2019 06:49:36
Advertisements