This is the solution for the challenge titled ChallengeDaysBetweenDates. This will be a fairly short solution, as the challenge itself is simple, but does have a few tricky parts to it.

Step 1: Default.aspx

To begin, create a new Project called ChallengeDaysBetweenDates and set it up as we have been so far in this series, with a Default.aspx page. Once that’s finished, switch to the Design view and add the following:


The programmatic ID’s for the controls are as follows:

  1. Calendar1
  2. Calendar2
  3. okButton
  4. resultLabel

Step 2: okButton_Click Event

Double-click the okButton to enter the okButton_Click EventHandler. The challenge specified that the resultLabel would display the number of days between dates regardless of which calendar’s date was larger. This requires conditional logic to solve.

Create an if() statement for the event that Calendar1’s date is larger than Calendar2. Inside that code block, write the following code:


What this code does is set the resultLabel’s Text property to the difference between Calendar1’s SelectedDate and Calendar2’s SelectedDate in days only.

Tip: I stress the use of TotalDays because if you were to leave out the TotalDays property, you would not have the proper result. TotalDays will give you the number of days without the hours, minutes, and seconds attached. This is the result without using this property:


Next, create an else() statement and copy the resultLabel.Text code into that code block. Then, simply change the calculation to subtract Calendar1’s SelectedDate from Calendar2’s:


The result will show the whole number difference for either case, regardless of which Calendar has a larger SelectedDate:


That concludes this solution. As was stated at the beginning, this challenge wasn’t difficult but it does require you to know the properties of the Calendar controls, as well as the DateTime and TimeSpan. Good job on completing this challenge! I encourage you, come back and do it again if you are struggling with any of the concepts. Review the Cheat Sheet and the lessons about Calendars and then retry. If you’d like, make it even better! Add some formatting to the calendars, make the resultLabel’s text friendlier, etc. Once you’re ready, proceed on to the next lesson.

Lessons in this Course