# 计算两个date之间的差异（天数）？

` `(EndDate - StartDate).TotalDays` `

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

` `DateTime d1 = DateTime.Now; DateTime d2 = DateTime.Now.AddDays(-1); TimeSpan t = d1 - d2; double NrOfDays = t.TotalDays;` `

` `(EndDate.Date - StartDate.Date).Days` `

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

` ` (a.Date - b.Date).TotalDays` `

` `EndDate.Date.Subtract(DateTime.Now.Date).Days` `

//天，小时和分钟的差异。

` `TimeSpan ts = EndDate - StartDate;` `

//天数差异

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

//时差。

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

//分钟差异

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

` `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();` `

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

` `int total_days = (EndDate - StartDate).TotalDays` `

` `DateTime strt_date = DateTime.Now; DateTime end_date = Convert.ToDateTime("10/1/2017 23:59:59"); //DateTime add_days = end_date.AddDays(1); TimeSpan nod = (end_date - strt_date); Console.WriteLine(strt_date + "" + end_date + "" + "" + nod.TotalHours + ""); Console.ReadKey();` `

` `int totalDays = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).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; } }` `