algolia / algoliasearch-jekyll

⚠ DEPRECATED Use jekyll-algolia instead.
https://community.algolia.com/jekyll-algolia/
MIT License
125 stars 12 forks source link

How to change the format of the date for search results. #11

Closed iloveip closed 9 years ago

iloveip commented 9 years ago

I would like to change the format of the date for search results. Now it is shown as "two days ago", etc. But I need to have the date in the following format: %Y-%m-%d (for example 2015-11-01). Because then I translate it into Russian using Liquid, as described here.

How can I do it?

pixelastic commented 9 years ago

By default, each post date is stored in the posted_at attribute as a timestamp. When doing a search query, the API will return this timestamp. You will then have to compute this value in the front-end before displaying it if you want to make it more readable.

In the Jekyll/Hyde demo, we use the awesome moment.js library to add a new key (posted_at_readable) to each result, right before displaying them. (Code here). You should be able to do something similar to display the date in Russian.

Another solution would be to pre-compute the %Y-%m-%d string before pushing it to Algolia, then you will just have to display it. This can be achieved in Ruby, AlgoliaSearchRecordExtractor.custom_hook_each(item, node) method we expose.

Hope this will get you started in the right direction

iloveip commented 9 years ago

@pixelastic thank you very much for the hint!

I added the following to my search.js file and it's working now:

moment.locale('ru', {
  months : "января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря".split("_")
});

function renderResults(data) {
  return $.map(data.hits, function(hit) {
    if (hit.posted_at) {
      moment.locale('ru');
      hit.posted_at_readable = moment.unix(hit.posted_at).format("D MMMM YYYY");
    }
    hit.css_selector = encodeURI(hit.css_selector);
    hit.full_url = config.baseurl + hit.url;

    return templateResult.render(hit);
  }).join('');
}
pixelastic commented 9 years ago

Perfect :)