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


当前回答

如果有人想要作为双精度的天数(a, b类型的DateTime):

 (a.Date - b.Date).TotalDays

其他回答

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

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 total_days = (EndDate - StartDate).TotalDays
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;

假设StartDate和EndDate是DateTime类型:

(EndDate - StartDate).TotalDays

使用TimeSpan对象,它是date减法的结果:

DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;