Question : Counting number of days between two dates using C#

Hi All,

I want to count the number of days from selected days.
I am having 2 calendar controls on the form. I want to select dates from each calendar and passing values to textbox1 and textbox2.
Lets say I am selecting 20/06/2010 from calendar1 and 25/06/2010 from calendar2.
I want to count the number of days and display as 6 to do some calculations.

I tried the following approach but it did not help. It just displays the total number of hours.

 DateTime checkInDate = Convert.ToDateTime(textbox1.Text);
        DateTime checkOutDate = Convert.ToDateTime(textbox2.Text);

        TimeSpan days = checkInDate.Subtract(checkOutDate);

The result is -120. I think it just gives the total number of hours as -120, but not the number of days.

Any ideas?

Thanks for your help.

Looking forward to your reply.

Answer : Counting number of days between two dates using C#

>> datepicker control picks the dates only in this format for example:  "MM/dd/yyyy"
and
>> textboxes in format "dd/MM/yyyy" then it works fine

I provided you the swap code, to make MM/dd/yyyy to dd/MM/yyyy

          textBox1.Text = ????? <---------------------- date from your control, then
          string[] temp = textBox1.Text.Split('/');
            string t = null;
           t = temp[1];
           temp[1] =  temp[0];
           temp[0] = t;
           textBox1.Text =  string.Join("/", temp); 'now it becomes dd/MM/yyyy format in textBox1and IF you have only dates in textbox1then this will
show you correct result:

           IFormatProvider culture = new CultureInfo("fr-FR", true);
           DateTime checkindate = DateTime.Parse(textBox1.Text, culture, DateTimeStyles.NoCurrentDateDefault);
           DateTime checkoutdate = DateTime.Parse(textBox2.Text, culture, DateTimeStyles.NoCurrentDateDefault);
           TimeSpan ts = checkoutdate.Subtract(checkindate);
           int daysOrTimeperiod = (int)Math.Abs(ts.Days);
           MessageBox.Show(daysOrTimeperiod.ToString());



Random Solutions  
 
programming4us programming4us