Click here to Skip to main content
15,899,314 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
if i select date 11/10/2011 in startdate textbox & 12/10/2011 in enddate textbox, then in days textbox it should display 2. but i am getting 1, pls help me.

C#
DateTime startDate = Convert.ToDateTime(txtStartDate.Text);
DateTime endDate = Convert.ToDateTime(txtEndDate.Text);

//
//if (!(endDate < startDate)) - [edit] replaced with below if
if (endDate > startDate)
{
    TimeSpan ts = endDate.Subtract(startDate);
    txtTotalDays.Text = ts.Days.ToString();
}
else
{
    Response.Write("End Date should be higher than Start Date");
}
Posted
Updated 10-Oct-11 23:53pm
v2
Comments
Xeshan Ahmed 11-Oct-11 5:55am    
why it should display 2 ?

(startDate  - endDate ).TotalDays
 
Share this answer
 
v3
I'd just use a TimeSpan class.
TimeSpan ts = endDate.Subtract(startDate);
 
Share this answer
 
Surely the difference between today and tomorrow is one day
 
Share this answer
 
No, it shouldn't. If you take any two numbers, you will get the same result. 12 - 11 = 1. It doesn't matter if it is two dates, or the number of beans in two tins.

If you want the number to be inclusive of partial days, you will have to add the one on manually:
C#
TimeSpan ts = endDate.Subtract(startDate);
txtTotalDays.Text = (ts.Days + 1).ToString();
 
Share this answer
 
Comments
jayanthik 11-Oct-11 5:56am    
yes tx

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900