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


当前回答

DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;

其他回答

DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    DateTime d = Calendar1.SelectedDate;
    // int a;
    TextBox2.Text = d.ToShortDateString();
    string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
    string s1 =  Convert.ToDateTime(Label7.Text).ToShortDateString();
    DateTime dt = Convert.ToDateTime(s).Date;
    DateTime dt1 = Convert.ToDateTime(s1).Date;
    if (dt <= dt1)
    {
        Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
    }
    else
    {
        string diff = dt.Subtract(dt1).ToString();
        Response.Write(diff);
        Label18.Text = diff;
        Session["diff"] = Label18.Text;
    }
}   

假设StartDate和EndDate是DateTime类型:

(EndDate - StartDate).TotalDays

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

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

date格式为"dd/MM/yyyy"

  string[] d1 = txtFromDate.Values.Split('/');
  string[] d2 = txtToDate.Values.Split('/');

  DateTime FrmDt = new DateTime(Convert.ToInt32(d1[2]), Convert.ToInt32(d1[1]), Convert.ToInt32(d1[0]));
  DateTime ToDt = new DateTime(Convert.ToInt32(d2[2]), Convert.ToInt32(d2[1]), Convert.ToInt32(d2[0]));

  TimeSpan TDiff = ToDt.Subtract(FrmDt);
  String DaysDiff = TDiff.TotalDays.ToString();