Monday, September 22, 2008

DateTime in CAML Query

Caml query not using the time part in datetime. If your are doing a caml query and you see that your time is being ignored in datetime try this:

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

You have to use IncludeTimeValue=”TRUE”.

You can use greator or equal like above and less or equal filter with AND operator in CAML above to work with date range.

If the date value is coming from your variable etc then you need to use SPUtility function and get the string required by CAML for date time variable.

DateTime CustomDate = DateTime.Now;
string strCustomDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(CustomDate);

This CAML Query below return the items based on MyDate with less than 10 days.
Basically using a Greator or Equal operatior and providing Today date - 10 days as a filter.

<Query>
<Where>
<Geq>
<FieldRef Name="MyDate" />
<Value Type="DateTime">
<Today OffsetDays="-10" />
</Value>
</Geq>
</Where>
</Query>