C#中的TimeSpan.FromHours()方法用于返回表示指定小时数的TimeSpan,其中指定的时间精确到最接近的毫秒。
语法如下-
public static TimeSpan FromHours (double val);
在上面,值val是精确到最接近毫秒的小时数。
现在让我们看一个例子-
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)); } }
输出结果
这将产生以下输出-
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
现在让我们来看另一个示例-
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)); } }
输出结果
这将产生以下输出-
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