Feb 26, 2015

Issue with datetime formats in OData retrievals

We now use OData Service for client side data retrievals. Yet, there is a bit of complexity when dealing with date time fields.  I usually use REST methods of XrmServiceToolkit library. When I try to retrieve datetime field and populate in some form field, I simply couldn’t do since what I retrieved was something different. Something like “/Date(1420588331000)/”. What is this?

This is a time encoded to a single integer which increases every second. This is UNIX timestamp. Though this is a logical representation of time which can be very helpful when dealing with complex time calculations, in our operation this can be frustrating.

We need to transfer this to date time which can be identified by JavaScript. So below code snippet can be helpful.

//Method

dateFormatUnixStamp: function (_uString) {
    var _date = null;
    if (_uString != null) {
        _date = new Date(parseInt(_uString.slice(_uString.indexOf("(") + 1, _uString.indexOf(")"))));
        _date.setDate(_date.getDate());
    }
    return _date;
}

//Calling

//Suppose _Ent is a entity we retrived through the service
//and we are assigning it to new_startdate of current form

var _startDate = dateFormatUnixStamp(_Ent.new_StartDate);
Xrm.Page.getAttribute(new_startdate).setValue(_startDate);

These two blogs also provides much helpful code samples in this regards;

https://rajeevpentyala.wordpress.com/2011/08/21/read-odata-service-date-field-in-crm-2011/
http://blogs.catapultsystems.com/rhutton/archive/2014/01/30/crm-2013-handling-odata-date-field-value.aspx

Thank you Deepak Mehta for the help.

No comments:

Post a Comment