我发现这个问题已经在Java、JavaScript和PHP中得到了解答,但c#中没有。那么,如何在c#中计算两个日期之间的天数呢?


当前回答

我认为这会达到你的目的:

DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);

TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;

其他回答

你可以使用下面的代码:

 int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds
// Difference in days, hours, and minutes.

TimeSpan ts = EndDate - StartDate;

// Difference in days.

int differenceInDays = ts.Days; // This is in int
double differenceInDays= ts.TotalDays; // This is in double

// Difference in Hours.
int differenceInHours = ts.Hours; // This is in int
double differenceInHours= ts.TotalHours; // This is in double

// Difference in Minutes.
int differenceInMinutes = ts.Minutes; // This is in int
double differenceInMinutes= ts.TotalMinutes; // This is in double

你也可以得到秒、毫秒和滴答的差异。

对于a和b作为两个DateTime类型:

DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();

得到两个日期之间的差值,然后从下面得到日期:

int total_days = (EndDate - StartDate).TotalDays
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;