C#程序获取两个日期之间的差异
用于DateTime.Subtract在C#中获取两个日期之间的差异。
首先,设置两个日期-
DateTime date1 = new DateTime(2018, 8, 27); DateTime date2 = new DateTime(2018, 8, 28);
使用Subtract方法来获得差异-
TimeSpan t = date2.Subtract(date1);
以下是完整的代码-
示例
using System; using System.Threading; using System.Diagnostics; public class Demo { public static void Main() { DateTime date1 = new DateTime(2018, 8, 27); DateTime date2 = new DateTime(2018, 8, 28); //得到差异 TimeSpan t = date2.Subtract(date1); Console.WriteLine(t); Console.WriteLine("Days (Difference) = {0} ", t.TotalDays); Console.WriteLine("Minutes (Difference) = {0}", t.TotalMinutes); } }输出结果
1.00:00:00 Days (Difference) = 1 Minutes (Difference) = 1440