Algolia Format Epoch Seconds To Date String (InstantSearch.js)

Use transformData of hits widget

Refer to InstantSearch.js hits for documentation.

Date accept value as epoch miliseconds ( the number of milliseconds since January 1, 1970, 00:00:00 UTC). Use Date.toISOString to output ISO format 2011-10-05T14:48:00.000Z. You can use slice to substring the first 10 characters.

search.addWidget(  instantsearch.widgets.hits({    container: '#hits',    templates: {      empty: 'No results',      item: '<p>{{ lastmod_date }}</p>'    },    transformData: {      item: function(data) {        // data.lastmod is epoch seconds        // Output: 2011-10-05        data.lastmod_date = new Date(data.lastmod*1000).toISOString().slice(0,10)        return data      }    }  }));

You can use Moment.js for more advance and reliable formatting. The drawback is the library size is a bit big (if you are using webpack, do check out Reduce Moment.js Npm File Size For Webpack)

moment(data.lastmod*1000).format('YYYY-MM-DD')

For various javascript implementation, refer to How to format a JavaScript date

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.