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

April 16, 2018
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.

    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)


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

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.