设置两个日期。
DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20); DateTime date2 = new DateTime(2018, 8, 17, 11, 14, 25);
现在,获取两个日期之间的差额。
TimeSpan ts = date2 - date1;
得到结果,即小时数差异。
ts.TotalHours
让我们看完整的代码。
using System; using System.Linq; public class Demo { public static void Main() { DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20); DateTime date2 = new DateTime(2018, 8, 17, 11, 14, 25); TimeSpan ts = date2 - date1; Console.WriteLine("No. of Hours (Difference) = {0}", ts.TotalHours); } }
输出结果
No. of Hours (Difference) = 794.984722222222