Wednesday, June 27, 2012

Dealing with Dates in ODATA Endpoints.

I quote from MSDN:

When you retrieve records using the REST endpoint date values are returned as strings that use the format “\/Date()\/” where is the number of milliseconds since midnight January 1, 1970. For example: "\/Date(1311170400000)\/". All values returned from Microsoft Dynamics CRM represent the Universal Coordinated time (UTC) values.

Sample Code:

Note: In the below code sample "result" is the response from the ODATA querry.

//Retrieving the Date object as string
var stringDateValue = eval(result.CreatedOn).toString();               

Once the string date values are converted to Date objects you can use a variety of JScript methods to display the date as a string that can be displayed in a user interface .

var createdOn  = new Date(parseInt(stringDateValue.replace("/Date(", "").replace(")/", ""), 10)); 
createdOn = getODataLocalDateFilter(createdOn);

function getODataLocalDateFilter(date) {
//-- Description: For converting the date object to local time format
//-- You can also convert this to UTC Date format
//-- UTC Usage: getUTCMonth(), getUTCFullYear(), getUTCHours() ...
 var monthString;
 var rawMonth = (date.getMonth()+1).toString();
 if (rawMonth.length == 1) {
  monthString = "0" + rawMonth;
 }
 else
 { monthString = rawMonth; }
 var dateString;
 var rawDate = date.getUTCDate().toString();
 if (rawDate.length == 1) {
  dateString = "0" + rawDate;
 }
 else
 { dateString = rawDate; }

 var DateFilter = "";
 DateFilter += date.getFullYear() + "-";
 DateFilter += monthString + "-";
 DateFilter += dateString;
 DateFilter += " T" + date.getHours() + ":";
 DateFilter += date.getMinutes() + ":";
 DateFilter += date.getSeconds() + ":";
 DateFilter += date.getMilliseconds();

 return DateFilter;
}

Have fun working with ODATA!!

1 comment:

Microsoft development said...

.NET development, ASP development, SharePoint development, Microsoft development , software development, Singapore – Total eBiz Solutions Home