Custom date formats with display templates

Display templates are used to show the queried results in a attractive and useful layout. With the CQWP we used XSLT to format the data as required, but with display templates we need to use JavaScript. One of my most formatted field are the date fields. In this blog post I will explain how you can change the format of a date field by using JavaScript.

Solution date format
1. Edit the related Item Template.
2. Add the ArticleStartDate to the ManagedPropertyMapping. For a clean example I removed all mappings besides Title and ArticleStartDate in the code below.

<mso:ManagedPropertyMapping msdt:dt="string">'Titel':'Title','ArticleStartDate':'ArticleStartDateOWSDATE'</mso:ManagedPropertyMapping>

3.  Create a variable for the ArticleStartDate column.

var ArticleStartDate = ctx.CurrentItem.ArticleStartDateOWSDATE;

4. To be able to format the date we need to create a new variable of the type Date.

var localArticleDate = new Date(ArticleStartDate);

5. Us the code below to display the ArticleStartDate with the required format.

<div>
   _#= localArticleDate.format("dd-MM-yyyy")
</div>

 

Result

CSWP Result

Share

2 Replies to “Custom date formats with display templates”

  1. Hi Ben, thanks for the code. Works well, but you missed =#_ from the end of the line in point 5.

Leave a Reply to bharat Cancel reply

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