# 如何在 C# 中计算两个日期之间的差异

Puneet Dobhal 2023年10月12日

``````DateTime sample_date = new DateTime(2010, 6, 14);
``````

## 使用 `-` 运算符计算 C# 中两个日期之间的差异

``````using System;
public class Sample {
public static void Main() {
DateTime date_1 = new DateTime(2019, 02, 12);
DateTime date_2 = new DateTime(2020, 04, 10);

/*Substraction (minus) of same data types yields difference in days*/
Console.WriteLine("Difference in days: " + (date_2 - date_1).Days);
}
}
``````

``````Difference in days: 423
``````

## 使用 `DateTime.Substract` 方法在 C# 中计算两个日期之间的差异

`DateTime.Subtract` 方法是另一种有效的方法。它返回两个日期之间的差，结果可以存储在 `TimeSpan` 数据类型中。

``````using System;
public class Sample {
public static void Main() {
DateTime date_1 = new DateTime(2019, 02, 12);
DateTime date_2 = new DateTime(2020, 04, 10);

TimeSpan Diff_dates = date_2.Subtract(date_1);
Console.WriteLine("Difference in days: " + Diff_dates.Days);
}
}
``````

``````Difference in days: 423
``````

`DateTime` 结构体也可以用来指定日期和时间。在这种情况下，使用 `DateTime.Subtract` 方法时，请确保日期在相同的时区中。否则，结果将包括时区之间的差异。

``````using System;
public class Sample {
public static void Main() {
/*Definations include time of day */
DateTime date_1 = new DateTime(2019, 02, 12, 8, 0, 0);
DateTime date_2 = new DateTime(2020, 04, 10, 12, 0, 0);

TimeSpan Diff_dates = date_2.Subtract(date_1);
Console.WriteLine("Difference in Days = " + Diff_dates.Days);
Console.WriteLine("Exact timespan in Days = " + Diff_dates.TotalDays);
}
}
``````

``````Difference in Days = 423
Exact timespan in Days = 423.166666666667
``````