Creating computed index Date field with custom formatting in Sitecore

Reading Time: 1 minute

There are couple of options how to index Date (DateTime) fields or basically any type of fields in Sitecore. You can use built in (computed) fields or you can create your own computed fields.

Built in computer fields can be found in Sitecore.ContentSearch assembly under Sitecore.ContentSearch.ComputedFields namespace. You can use for example CreatedDate and UpdatedDate classes from there to do the job.

In this blog posts I will show you the latter option.

You can use custom computed fields that I have made below if you need to have a special formatted date and do not want to recompile code each time the format changes but want to just change configuration. There are various other reasons why to use custom computed fields…

Definition of the custom computed field would be:

​​<field fieldName=”Date” referencedFieldName=”__Updated” dateFormatPattern=”yyyyMMdd”>ToTheCoreSk.SC.Foundation.Search.ComputedFields.DateField, ToTheCoreSk.SC.Foundation.Search</field>

This definition needs to be placed under this element <fields hint=”raw:AddComputedIndexField”> under your Index Configuration definition <CustomIndexConfiguration> element in config. See patch file in my gist embedded below to inspire.

Let’s quickly take a look what parameters can be configured in field definition:

  • fieldName – Name of field in index
  • referencedFieldName – Name of field in Sitecore
  • dateFormatPattern – Date pattern used for formatting -> See Microsoft documentation for further details – In this case (yyyyMMdd) the output would be 20190527

 

And this is the patch file to add this computed field to my custom index (adjust it based on your needs) and also definition of my custom computed field that you need to incorporate into your solution:

Code is self explanatory I think 🙂

Happy coding!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.