Getting current events from a Calendar list
Posted
Friday, July 25, 2008 1:39 PM
by
Itay Shakury
You have a calendar list. You want to query it for events that happen right now. Not today, not this week, right this moment. Yes, including reoccurring events. I really thought it would be easier, or at least hoped to find a working example somewhere...
Anyway, here is the CAML that I ended up with:
<Where>
<And>
<DateRangesOverlap>
<FieldRef Name="EventDate" />
<FieldRef Name="EndDate" />
<FieldRef Name="RecurrenceID" />
<Value Type="DateTime" IncludeTimeValue="TRUE">
<Today />
</Value>
</DateRangesOverlap>
<And>
<Geq>
<FieldRef Name="EndDate" />
<Value Type="DateTime" IncludeTimeValue="TRUE">
<Today />
</Value>
</Geq>
<Leq>
<FieldRef Name="EventDate" />
<Value Type="DateTime" IncludeTimeValue="TRUE">
<Today />
</Value>
</Leq>
</And>
</And>
</Where>
The first part gets all the events for today, including reoccurring events, and the second one checks for the time. Put the both inside <And> section, and you get all the events for now.
DatesOverlap is used to query for reoccurring events, it needs some configuring of the SPQuery object to work.
Here is how it all fits togeather in code:
SPList list = SPWeb.Lists["Calendar"];
SPQuery q = new SPQuery();
q.CalendarDate = DateTime.Now;
q.ExpandRecurrence = true;
q.Query = "<Where>...</Where>"; //Full CAML omitted for clarity, just paste the code from above
SPListItemCollection items = list.GetItems(q);
Hope this saves you the time I spent.