I'm using SharePoint's rest api to get the coming events in a calendar, with the following query:
/_api/Web/Lists/GetByTitle('Agenda')/Items?$top=3
How can I change this query to get only events for which the EventDate
is superior to today ?
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It only takes a minute to sign up.
Sign up to join this communityI'm using SharePoint's rest api to get the coming events in a calendar, with the following query:
/_api/Web/Lists/GetByTitle('Agenda')/Items?$top=3
How can I change this query to get only events for which the EventDate
is superior to today ?
Add $filter
in your query URL
var today = new Date();
/_api/Web/Lists/GetByTitle('Agenda')/Items?$filter=EventDate ge '"+today.toISOString()+"'&$top=3
Following syntax is not needed. Only ge '"+today.toISOString()+"'
is enough.
ge datetime'" + today.toISOString() + "'
As you cannot filter on the EventDate column with the $filter parameter in the REST api, you can use a Caml query like this:
var date = new Date();
$.ajax({
url: "/_api/web/lists/getbytitle('Agenda')/getitems",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
},
data: JSON.stringify({
query: {
__metadata: {
type: "SP.CamlQuery"
},
ViewXml: "<View><Query><Where><Gt><FieldRef Name='EventDate' /><Value Type='DateTime' IncludeTimeValue='TRUE'>" + date.toISOString() + "</Value></Gt></Where></Query><RowLimit>3</RowLimit></View>"
}
}),
success: function (d) {
console.log(d);
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
You can get future only events for both recurring and non recurring events. Firstly you will have to create managed properties (in my case - EventStartTime
, and EventEndTime
) for both start date and end date of type date type (RefinableDate in SharePoint online) and the using them in your query text. To build search API query try using SPQuery builder tool on CodePlex.
By the way, query will be like below -
https://<<Site URL>>/_api/search/query?querytext='ListId:<<List ID>>'&trimduplicates=false&selectproperties='Title,Description,DescriptionOWSMTXT'&refiners='ContentClass:STS_ListItem'&refinementfilters='or(and(EventStartTime:range(min," + new Date().toISOString() + ",to=\"le\"),EventEndTime:range(" + new Date().toISOString() + ",max,from=\"ge\")),EventStartTime:range(" + new Date().toISOString() + ",max,from=\"ge\"))'&rowlimit=100