Filtering CAML queries by time values

When querying a SharePoint list, or creating a view, you can filter using the built-in keyword Today. However, the Today keyword will not return the time, only the date when using a CAML query.

First of all, you need to mark the query filter value with IncludeTimeValue as:

 <Value IncludeTimeValue='TRUE' Type='DateTime'><Today /></Value>

However, as the Today field has no time information, this will fail. Instead, create a local variable

string today = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ");

In the following example, I am doing a filter on publishing start and end date, with working result.

string today = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ");
CamlQuery query
= new CamlQuery
{
ViewXml
= @"<View>
<Query>
<Where><Or><And>
<Or>
<Leq><FieldRef Name='PublishingStartDate' />
<Value IncludeTimeValue='TRUE' Type='DateTime'>
" + today + @"</Value></Leq>
<IsNull><FieldRef Name='PublishingStartDate' /></IsNull>
</Or>
<IsNull><FieldRef Name='PublishingExpirationDate' /></IsNull>
</And>
<Geq><FieldRef Name='PublishingExpirationDate' />
<Value IncludeTimeValue='TRUE' Type='DateTime'>
" + today + @"</Value></Geq>
</Or></Where>
</Query></View>
"
};

Hope this helps!