Tuesday, January 17, 2017

Making sure the Time Component is accounted for in a DateTime CAML Query

The key to making certain that the time component is leveraged when you're performing a datetime comparison in a CAML Query is to include the IncludeTimeValue attribute in your query with a value set to "TRUE".

In the following example, I leveraged a javascript CSOM CAML query to only return items in my image library called "Banners" in which the current datetime falls within the boundaries specified in my custom StartDate and EndDate datetime fields of the image library:

<View>
 <Query>
  <Where>
   <And>
    <Leq>
     <FieldRef Name=\'StartDate\'/><Value IncludeTimeValue=\'TRUE\' Type=\'DateTime\'><Today /></Value>
    </Leq>
    <Geq>
     <FieldRef Name=\'EndDate\'/><Value IncludeTimeValue=\'TRUE\' Type=\'DateTime\'><Today /></Value>
    </Geq>
   </And>
  </Where>
 </Query>
</View>

Here is a more complete version of the code that I used:

function execRequest_Banner() {
     var ctx_Banner = SP.ClientContext.get_current();
     var camlQuery_Banner = new SP.CamlQuery();
     // Filter the image to display based on the following criteria:
     // 1) Only display images in which today's date falls within the Start and End Date range
     // specified

     camlQuery_Banner.set_viewXml('<View><Query><Where><And><Leq><FieldRef Name=\'StartDate\'/>
<Value Type=\'DateTime\'><Today /></Value></Leq><Geq><FieldRef Name=\'EndDate\'/>
<Value IncludeTimeValue=\'TRUE\' Type=\'DateTime\'><Today /></Value></Geq></And>
</Where></Query></View>');
     this.items_Banner = 
     ctx_Banner.get_web().get_lists().getByTitle('Banners').getItems(camlQuery_Banner);
     ctx_Banner.load(items_Banner);
     ctx_Banner.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded_Banner),
     Function.createDelegate(this, this.onQueryFailed_Banner));
}