0

I am making a web page in that I have used Ajax calendar to pick two date like TO date and From date and I also have a Textbox of total days.

So when user selects to and from dates, the difference of these dates is displayed in the textbox. So how can I find the difference of these dates..?

I set the format like dd/MM/yyyy.

e.g.

one textbox has: 20/04/2012  
second has     : 02/05/2012

So, please find difference on these ?

Thanks in Advance....
Mitesh

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mitesh Machhi
  • 203
  • 2
  • 5
  • 18
  • Please check my removal of AJAX tag (assuming you want to do it server side as tagged with C#). If you need it browser side - add JavaScript tag and possible ajax. – Alexei Levenkov Jul 02 '12 at 05:58
  • yes when to date is select and then from_date is select, direct diff. is displayed in next textbox of total days. i want to do at sever side. – Mitesh Machhi Jul 02 '12 at 06:00
  • possible duplicate of [How do I get the number of days between two dates in jQuery?](http://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-jquery) – V4Vendetta Jul 02 '12 at 06:04

4 Answers4

8

Substraction operator (-) works on DateTime

DateTime to_datetime = DateTime.ParseExact(to_textbox.Text, "dd/MM/yyyy", 
                                           CultureInfo.InvariantCulture);
DateTime from_datetime = DateTime.ParseExact(from_textbox.Text, "dd/MM/yyyy", 
                                             CultureInfo.InvariantCulture);

Timespan result  = to_datetime - from_datetime;

You can use it as

textBox1.Text = (to_datetime - from_datetime).TotalDays.ToString();
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
3

Convert your textbox values to date using:

DateTime dt1 = DateTime.ParseExact(textbox1.Text, "d/M/yyyy", CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.ParseExact(textbox2.Text, "d/M/yyyy", CultureInfo.InvariantCulture);

Use TimeSpane

    TimeSpan ts = dt1.Subtract(dt2);
    Console.Write(ts.TotalDays);
    textBox3.Text = ts.TotalDays;
Habib
  • 219,104
  • 29
  • 407
  • 436
1

Assuming C# code: DateTime support "-" that results in TimeSpan object.

DateTime nowTime = DateTime.Now;
DateTime yesterday = nowTime.AddDay(-1);
TimeSpan diff = nowTime - yesterday;
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0
DateTime date1 =DateTime.ParseExact("20/04/2012","d/M/yyyy",null);
 DateTime date2 = DateTime.ParseExact("02/05/2012", "d/M/yyyy", null); 
 TimeSpan datediff = date2 - date1;
 Response.Write(datediff.ToString());
Satinder singh
  • 10,100
  • 16
  • 60
  • 102