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


当前回答

// 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

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

其他回答

对于像我这样的初学者来说,在简单的一行代码中就会遇到这个小问题:

int totalDays = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).TotalDays);

这将计算从今天(DateTime.UtcNow.Date)到所需日期(myDateTime.Date)的总天数。

如果myDateTime是昨天,或比今天更早的日期,这将给出一个正(+)整数结果。

另一方面,如果myDateTime是明天或未来的日期,由于加法规则,这将给出一个负(-)整数结果。

编码快乐!^ _ ^

你可以试试这个

EndDate.Date.Subtract(DateTime.Now.Date).Days
// 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

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

首先声明一个稍后会返回的类:

public void date()
{
    Datetime startdate;
    Datetime enddate;
    Timespan remaindate;

    startdate = DateTime.Parse(txtstartdate.Text).Date;
    enddate = DateTime.Parse(txtenddate.Text).Date;

    remaindate = enddate - startdate;

    if (remaindate != null)
    {
        lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
    }
    else
    {
        lblmsg.Text = "correct your code again.";
    }
}

protected void btncal_Click(object sender, EventArgs e)
{
    date();
}

使用按钮控件调用上面的类。这里有一个例子:

你可以使用下面的代码:

 int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds