Click here to Skip to main content
15,668,848 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
i have to calenders
and two textboxes

one is from : textbox1 and calender1
2nd is to : textbox2 and calender2

when i select a date .. in calender1 it shows slectd date in textbox1
and when i select a date .. in calender2 it shows me selectd date in textbox2

Now i placed a label . in which i want that the days between the two 'FROM' and 'TO' TEXTBOXES will b shown in in LABEl

when i selectd FROM date : 23/3/2012
and TO date : 2/4/2012

the label show me the number of days in LABEL . in this case.. which will be "7 DAYS"

i tries to do this task with this code

protected void Button1_Click(object sender, EventArgs e) 
           DateTime dt1 = Calendar1.SelectedDate; 
           DateTime dt2 = Calendar2.SelectedDate; 
           TimeSpan ts = dt2 - dt1; 
           int numberOfDays = ts.Days; 
           Label3.Text = numberOfDays.ToString(); 

but not found my desired result,

I think the method used is good.
Regarding Conversion of Date from string, if the Parse method is used then
Formatting is influenced by properties of the current DateTimeFormatInfo object, which by default are derived from the Regional and Language Options item in Control Panel. One reason the Parse method can unexpectedly throw FormatException is if the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator properties are set to the same value. as explained here[^]

Hence, if the Format of date being displayed in the TextBox is fixed, let us say dd/MM/yyyy, then the ParseExact method explained here[^] where CultureInfo.InvariantCulture is recommended in the Note for custom format, may be better as shown below
DateTime dt2 = DateTime.ParseExact("02/04/2012","dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

Further these two statements
int numberOfDays = ts.Days;
Label1.Text = numberOfDays.ToString();

can be combined as
Label1.Text = ts.Days.ToString();

if there is no other purpose for numberOfDays.
Share this answer
Espen Harlinn 28-Apr-12 5:48am    
VJ Reddy 28-Apr-12 5:58am    
Thank you, Espen.
Sandeep Mewara 28-Apr-12 7:26am    
5'ed! :)
VJ Reddy 28-Apr-12 7:34am    
Thank you, Sandeep.
syed armaan hussain 28-Apr-12 8:22am    
thumbz up x 5! man
Hi Friend...

U can also try this

date1 = "23/03/1989"
date2 = "28/04/2012"
ts = date2.Subtract(date1)  

iNumberOfDays = ts.Days  

strMsgText = "The total number of days elapsed since " _  
& date1.ToShortDateString() & " is: " & iNumberOfDays.ToString()
Share this answer

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