Fetching Data Based On Date Field Using WebAPI

This article is about using WebAPI request for datatime field in Dynamics 365 CE

Introduction

 
Are you looking for sample code to fetch data from Dynamics 365 CE using WebAPI? If yes, this post will help. We are discussing how to fetch the data based on the datetime field from the account entity.
 
Requirement

Retrieve account records which were created on or before today’s date.

Solution

 
While writing a Web API request, the first thing to make sure of is to check all the available filters that we can use in our WebAPI request. You can get full details of supported filters here.
 
Now, our requirement is to compare the data based on the current date, so the first thing we need is to get the current data and format it correctly using libraries, like Moment.js, or you can manually format it using the following.
  1. function FormatDate() {  
  2.     var today = new Date();  
  3.     var month = today.getMonth() + 1; //to use correct month, it will return 0 for jan  
  4.     var day = today.getDate();  
  5.     var year = today.getFullYear();  
  6.     return month + "-" + day + "-" + year;  
  7. }  
The above function will get the current date and will format it with what we need to query the Dynamics 365 CE. Now, we can use it in our WebAPI request.
 
In the following example, I am going to query the account entity record which is created today or before.
  1. function retrieveAccounts() {  
  2.       
  3.     var currentDate = FormatDate();  
  4.     var entity = "accounts";  
  5.     var columnSet = "?$select=name&$filter=createdon le '" + currentDate + "'&$count=true";  
  6.     var serverURL = Xrm.Page.context.getClientUrl();  
  7.     var Query = entity + columnSet;  
  8.     var req = new XMLHttpRequest();  
  9.     req.open("GET", serverURL + "/api/data/v9.0/" + Query, true);  
  10.     req.setRequestHeader("Accept""application/json");  
  11.     req.setRequestHeader("Content-Type""application/json; charset=utf-8");  
  12.     req.setRequestHeader("OData-MaxVersion""4.0");  
  13.     req.setRequestHeader("OData-Version""4.0");  
  14.      
  15.     req.onreadystatechange = function() {  
  16.         if (this.readyState == 4 /* complete */ ) {  
  17.             req.onreadystatechange = null;  
  18.             if (this.status == 200) {  
  19.                 var data = JSON.parse(this.response);  
  20.                 if (data['@odata.count'] != null)  
  21.                     alert("Total Records:"+ data['@odata.count']);   
  22.             } else {  
  23.                 var error = JSON.parse(this.response).error;  
  24.                 alert(error.message);  
  25.             }  
  26.         }  
  27.     };  
  28.     req.send();  
  29. }  

I hope this will help someone!