Search, SharePoint, Technical

Format Date on Search Results

In building a custom display template for search results I found myself in an interesting scenario. The display template needed to make a REST call back into SharePoint 2013 to get additional info for display and one of the properties in that result was a date field. When making a call through the API like this, SharePoint will return the date in ISO format (i.e. YYYY-MM-DDTHH:mm:ss.sssZ.) Since this REST call is done client side through JavaScript, my default inclination was to format the date using

var myDate = isoStringReturnedFromRESTCall;
var displayDate = new Date(myDate);

Then either pull out what I needed from displayDate, or format it appropriately when creating the Date object. All is good there, except I needed to support IE8. Turns out IE8 doesn’t support creating Date objects from an ISO date format, it throws an “Invalid Date” error. Crap.

To get around this, I ended up creating the date object from Date.UTC after splitting out the appropriate components from the ISO date string. Here’s what that looks like:

var updateDateStr = isoStringReturnedFromRESTCall;
var updateDateArray = updateDateStr.split(‘T’);
var dateArray = updateDateArray[0].split(‘-‘);
var timeArray = updateDateArray[1].split(‘:’);
var updateDate = new Date(Date.UTC(dateArray[0], dateArray[1]-1, dateArray[2], timeArray[0], timeArray[1], 00));

From there I could interact with updateDate as a normal Date object.

Leave a Reply

Your email address will not be published. Required fields are marked *