Using date ranges in CAML queries

The following code is the easiest way I have found to retieve items from a list using a date range.

Microsoft.SharePoint.SPQuery camlQuery = new Microsoft.SharePoint.SPQuery();
camlQuery.Query = @"<Where>
                      <DateRangesOverlap>
                        <FieldRef Name=""EventDate""></FieldRef>
                        <FieldRef Name=""EndDate""></FieldRef>
                        <Value Type=""DateTime"">
                          <Now/>
                        </Value>
                      </DateRangesOverlap>
                    </Where>
                    <OrderBy>
                      <FieldRef Ascending='TRUE' Name='EventDate' Type='DateTime' />
                    </OrderBy>";
This entry was posted in SharePoint and tagged , . Bookmark the permalink.

2 Responses to Using date ranges in CAML queries

  1. ceej says:

    1. What exactly does the above query give us results-wise? All those items where the value of Now falls between the values of EventDate and EndDate?

    2. What about using something similar to the following to retrieve items which match a date range? In this example all items which were created in the last seven days.

    	<Where>
    		<Geq>
    			<FieldRef Name="Created" />
    			<Value Type="DateTime">
    				<Today OffsetDays="-7" />
    			</Value>
    		</Geq>
    	</Where>
    
    • frogman says:

      1. I used the query in a webpart that only displays current events. The events are stored in a SharePoint calendar, a selection of the current events, those which have an EventDate < = Now and EndDate >= Now, are surfaced in the web part used on the home page.

      2. A valid point which I am sure would have many uses. Thanks ceej.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>