how to display current month items from SharePoint list with query.
2 Answers
Use SPUtility.CreateISO8601DateTimeFromSystemDateTime to create relevant DateTime string.
DateTime firstDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
string firstDayValue = SPUtility.CreateISO8601DateTimeFromSystemDateTime(firstDay);
string firstDayValueplus1Month = SPUtility.CreateISO8601DateTimeFromSystemDateTime(firstDay.AddMonths(1));
SPQuery query = new SPQuery();
query.Query = "<Where><And><Geq><FieldRef Name='Date' /><Value Type='DateTime'>" + firstDayValue +
"</Value></Geq><Leq><FieldRef Name='Date' /><Value Type='DateTime'>" + firstDayValueplus1Month +
"</Value></Leq></And></Where>";
-
-
@Venu, I have modified and updated the code, please check it and let us know. Mar 21, 2014 at 8:04
-
@Venu If you have recurring events, for example, the event which repeats every two days. In this request you retrieve only one of them, because SharePoint stores recurring items as a point to calculation, range for the next events and it's count. Mar 21, 2014 at 14:55
If your calendar has recurring items the query from Karthik Jaganathan's answer works incorrect. The best method is use attribute DateRangesOverlap.
oQuery.Query = "<Where><DateRangesOverlap><FieldRef Name='EventDate' /><FieldRef Name='EndDate' /><FieldRef Name='RecurrenceID' /><Value Type='DateTime'><Today /></Value></DateRangesOverlap></Where>"
See this blog for more info
-
Your query returns every event where start & end overlap with today, correct ? Which is not what the OP asked. Mar 21, 2014 at 8:08
-
@CameronVerhelst please clarify your question. DateRangesOverlap returns all events in range Today, Week, Month, Year depends on attribute in query. See the link which is provided in the answer. If I'm not wrong the default SharePoint calendar uses this query. Mar 21, 2014 at 14:57
-
Aha, indeed I should've looked throught the blog. Basically I was alluding to the use of <Today /> in your query. The blog mentions you can use week and month (<Month />) which is what the OP needs I think. Mar 21, 2014 at 15:09