Convert timestamp in refinement list

I have filters setup to refine by timestamp, but need to exclude these from the Current Refinement list as the just show as the timestamp (which won’t make sense to users)

In the Refinement List output, is there a way to convert these timestamps to human readable dates?

NB - am using instantsearch js

Many Thanks

Guy

Hello @guy3,
Could you provide us more information like some part of your records showing how they look like, or the current UI that you’re working on?

If I understand correctly, you have a refinementList and eacc item is a timestamp (number), correct?

You can rename the label of the facets with transformItems.

instantsearch.widgets.refinementList({
  // ...
  transformItems(items) {
    return items.map(item => ({
      ...item,
      label: convertToHumanReadableLabel(item)
    }));
  },
});

Let us know how it goes and if you have any question!

Hi Eunjae

At the moment I have

search.addWidget(
  instantsearch.widgets.currentRefinements({
    container: '#current-refinements',
    excludedAttributes: ['instances'],
  })
);

If I remove the exclusion I get :e.g.

image
I also have other bits in the refinement list e.g. categories - can I change the labels just for the timestamps?

image

Thanks

Guy

Hi @guy3,
For currentRefinements widget, you can use transformItems as well.

  instantsearch.widgets.currentRefinements({
    container: '#current-refinements',
    transformItems: items => {
      console.log(items);
      return items;
    },
  }),

You can pick the timestamp attribute with attribute key and modify the values of the refinements. Please see the console log below.

Does it make sense to you?

Thanks for the help so far - unfortunately, I’m still not quite getting how I can turn:

​​​________

attribute: “instances”

label: “≥ 1596582000”
​​​​
operator: “>=”
​​​​
type: “numeric”
​​​​
value: 1596582000


into something like “From 5 Aug”

Thanks

Guy

Hey @guy3

const date = new Date(item.value * 1000) // item.value === 1596582000

You can format date with many different ways like using date-fns, moment.js, or even with Intl.DateTimeFormat (be aware of its browser compatibility, though).

For example, with Intl.DateTimeFormat,

const dateStr = Intl.DateTimeFormat("en-US", { month: 'short', day: 'numeric' }).format(date); // -> "Aug 1"

const op = operator === ">=" ? "From" : "To";

const label = `${op} ${dateStr}`; // -> "From Aug 1"

I hope this works for you.