ASP.NET Calendar Date Range

One of my current projects includes a web-based event calendar.  During development I realized that the Calendar control did not have a property or method that would return the first and last date displayed by the control.  The following code does just that.

DateTime firstDate = Calendar1.VisibleDate;
DayOfWeek firstDOW;

if (Calendar1.FirstDayOfWeek == System.Web.UI.WebControls.FirstDayOfWeek.Default)
 firstDOW = System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek;
else
 firstDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), Calendar1.FirstDayOfWeek.ToString());

if (firstDOW == Calendar1.VisibleDate.DayOfWeek)
 firstDate = firstDate.AddDays(-7);
else
 while (firstDate.DayOfWeek != firstDOW)
  firstDate = firstDate.AddDays(-1);

DateTime lastDate = firstDate.AddDays(41);

The Calendar's FirstDayOfWeek property returns a System.Web.UI.WebControls.FirstDayOfWeek enumeration member. It includes all of the members of the System.DayOfWeek enumeration plus a "Default" member, which is equal to System.Globalization.DateTimeFormatInfo.CurrentInfo.
FirstDayOfWeek.  In order to work with the DateTime.DayOfWeek property, I convert the FirstDayOfWeek value to a DayOfWeek and store it in a temporary variable named firstDOW. 

Finding the value for the first date displayed by the Calendar Control is accomplished by checking the DayOfWeek property of the firstDate variable, which is initialized to Calendar1.VisibleDate (always returns the 1st day of the visible month).  If firstDate.DayOfWeek is equal to Calendar1.VisibleDate.DayOfWeek then an entire week is subtracted from the initial value to obtain the first displayed date.  If the firstDate.DayOfWeek is not equal to Calendar1.VisibleDate.DayOfWeek then a day is subtracted from the firstDate variable until the firstDate.DayOfWeek is equal to firstDOW.

It seems the Calendar Control always displays six rows, even if the last column of the fifth row is from the next month.  This behavior makes it easy to calculate the last displayed date - simply add 41 days to the first displayed date.

2 comments

1. at 2:27 PM on Jun 28, 2008, Ken wrote:
Simply genius! I always wished there were properties like Calendar1.FromDate & Calendar1.ToDate available. Your code ROCKS! THANK YOU SO MUCH FOR SHARING!
2. at 12:41 PM on Jan 28, 2009, dan wrote:
Just what I needed. Thanks Once I added "first date" in quotes to my search you came up first!

Related Entries

no entries found