Click here to Skip to main content
15,895,606 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have three TextBoxes:
XML
TextBox1 contains fromdate

XML
TextBox2 contains todate

Both Textboxes are having 'Date' Text Mode in 'dd/MM/yyyy' format

I want to find the number of days between these two and put value in third TextBox.
I tried 'Subtract', 'TimeStamp' but didn't work.
Please Help...
This is the Code:

C#
DateTime fromDate, toDate;
       fromDate = Convert.ToDateTime(txt_fromdate.Text);
       toDate = Convert.ToDateTime(txt_todate.Text);

       DateTime fromdate = DateTime.MinValue;
       DateTime todate = DateTime.MaxValue;</pre>
       TimeSpan noofdays = todate - fromdate;
       txt_noofdays.Text = noofdays.ToString();
Posted
Updated 11-Jan-16 19:10pm
v2
Comments
Sergey Alexandrovich Kryukov 12-Jan-16 1:04am    
"Didn't work" is not informative. It does work.
—SA
Member 12133159 12-Jan-16 1:07am    
I am getting wrong value when Entering fromdate=12/01/2016 todate=20/01/2016; Result= '3652058.23:59:59.9999999' While it should return '8'.....
Sergey Alexandrovich Kryukov 12-Jan-16 1:13am    
What's wrong with reading original MSDN documentation?
—SA

 
Share this answer
 
Comments
Member 12133159 12-Jan-16 1:43am    
I already visited these links...
Everything is working but the only problem is I have Dates in TextBoxes...
deepankarbhatnagar 12-Jan-16 1:55am    
convert that string to datetime by typecasting
Member 12133159 12-Jan-16 2:13am    
I tried that too but it didn't work and displayed an error 'String was not in Date/Time format' something like that.....
deepankarbhatnagar 12-Jan-16 2:16am    
try : support your textbox is txt1 then

DateTime dt1 = Convert.ToDateTime(txt1.Text);
Member 12133159 12-Jan-16 2:22am    
Thanks a lot Sir, It worked finely...
I don't know what was the problem when i tried this earlier...
Well, Thanks again... :)
Please see my comment to the question. Yes, it's "subtract" and also System.TimeSpan. Use subtraction properly:
C#
System.DateTime before = //...
System.DateTime after = //...
System.TimeSpan interval = before - after; // as simple as that;
// the operator '-' is defined for the DateTime struct

The further code depends on what you mean by the meaning of "number of days". If you think about it, you may understand that these words are ambiguous. But, for example,
C#
int numberOfDays = interval.Days;
double intervalInDays = interval.TotalDays;
Please see:
DateTime Structure (System)[^],
TimeSpan Structure (System)[^].
Member 12133159 wrote:

I already visited these links...
Everything is working but the only problem is I have Dates in TextBoxes...
Read on the methods named as System.DateTime.*Parse*; the link is shown above.

—SA
 
Share this answer
 
v3

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