CAML Query using Date Ranges

Having trouble getting any results back when querying a SharePoint list for items within a date range? It may be that you haven’t converted your variable dates to the ISO 8601 format that SharePoint expects for date values in CAML queries. You can do this by using the SPUtility.CreateISO8601DateTimeFromSystemDateTime() method. Make sure the dates you are converting are in UTC or local time first though!

An example is below:

string Iso8601startDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(startDate);

string Iso8601Today = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Today.AddDays(1));

            if (spList != null)

            {

                SPQuery qry = new SPQuery();

                qry.Query =

                @”   <Where>

                          <And>

                             <Gt>

                                <FieldRef Name=’DateSubmitted’ />

                                <Value Type=’DateTime’ IncludeTimeValue=’FALSE’>” + Iso8601startDate +

                                @” </Value>

                             </Gt>

                             <Lt>

                                <FieldRef Name=’DateSubmitted’ />

                                <Value Type=’DateTime’ IncludeTimeValue=’FALSE’>” + Iso8601Today +

                                @”</Value>

                             </Lt>

                          </And>

                       </Where>

                       <OrderBy>

                          <FieldRef Name=’DateSubmitted’ />

                       </OrderBy>”;

 

 

 

Advertisements