> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Sort an index by date

> How to sort your records by date.

By design, Algolia provides one [ranking strategy](/doc/guides/managing-results/relevance-overview/in-depth/ranking-criteria) per [index](/doc/guides/sending-and-managing-data/prepare-your-data/in-depth/prepare-data-in-depth#algolia-index): when you want to provide different rankings for the same data, **you need to use different indices for each ranking**.
These indices are called [replicas](/doc/guides/managing-results/refine-results/sorting/in-depth/replicas).

<Note>
  To set up sorting by attribute,
  you need to understand how [replica indices](/doc/guides/managing-results/refine-results/sorting/in-depth/replicas) work.
</Note>

To sort by attribute, create a replica index and then change the ranking formula of the replica.
You can do this from Algolia's dashboard or through the API.

For chronological sorting, consider [how Algolia handles dates](/doc/guides/sending-and-managing-data/prepare-your-data/in-depth/what-is-in-a-record#dates).
For example, you have a blog and want to create a replica to sort search results from the most recent to the oldest post.
Because Algolia doesn't interpret dates as ISO 8601 strings (such as "2008-09-15T15:53:00"),
**you must convert your dates into Unix timestamps** (numeric values such as 1221486780) before sorting them.

## Convert dates into Unix timestamps: an example

### Before

Say you have an index called `articles`:

```json JSON icon=braces theme={"system"}
[
  {
    "post_title": "Let's start the adventure",
    "post_date": "2012-07-01",
    "author_name": "Nicolas Dessaigne",
    "author_image_url": "https://secure.gravatar.com/avatar/785489bc2ac2e08ae66648a8936c1101?s=40&d=mm&r=g",
    "permalink": "https://blog.algolia.com/lets-start-the-adventure/",
    "excerpt": "Welcome to The Algolia Blog! It's always difficult to write the first post of a blog! What should I talk about? The company, the founders, the business, the culture? And all that knowing that virtually nobody will read except diggers in a few years (hopefully)!\nLet's concentrate instead on what we'll be blogging about. Company news obviously, but not only. I expect we'll write quite a few posts about technology, algorithms, entrepreneurship, marketing, and whatever else we'll want to share with you 🙂\nAnd most important, feel free to participate in comments or by contacting us directly. We appreciate your feedback!\nWelcome to the Algolia blog!"
  },
  {
    "post_title": "Great discussions at LeWeb'12 London",
    "post_date": "2012-07-03",
    "author_name": "Nicolas Dessaigne",
    "author_image_url": "https://secure.gravatar.com/avatar/785489bc2ac2e08ae66648a8936c1101?s=40&d=mm&r=g",
    "permalink": "https://blog.algolia.com/great-discussions-at-leweb12-london/",
    "image": "https://blog.algolia.com/wp-content/uploads/2014/03/latency-360x200.png",
    "excerpt": "… take long for us to decide it was the way to go, since the perception of speed is so natural that the benefit far outweighs the longer integration code. We'll now work on simplifying it!\nWe'll soon do a post about this demo. In the meantime, stay tuned!\n&nbsp;\n&nbsp;"
  }
]
```

### After

You want to create a replica that sorts your data by date. The problem is that the `post_date` attribute has dates formatted as strings, which Algolia can't process for sorting. Before creating a replica, you must transform these dates into [Unix timestamps](https://wikipedia.org/wiki/Unix_time).

You don't have to remove or change `post_date`. Add a `post_date_timestamp` attribute with the proper format instead.

```json JSON icon=braces theme={"system"}
[
  {
    "post_title": "Let's start the adventure",
    "post_date": "2012-07-01",
    "post_date_timestamp": 1341100800,
    "author_name": "Nicolas Dessaigne",
    "author_image_url": "https://secure.gravatar.com/avatar/785489bc2ac2e08ae66648a8936c1101?s=40&d=mm&r=g",
    "permalink": "https://blog.algolia.com/lets-start-the-adventure/",
    "excerpt": "Welcome to The Algolia Blog! It's always difficult to write the first post of a blog! What should I talk about? The company, the founders, the business, the culture? And all that knowing that virtually nobody will read except diggers in a few years (hopefully)!\nLet's concentrate instead on what we'll be blogging about. Company news obviously, but not only. I expect we'll write quite a few posts about technology, algorithms, entrepreneurship, marketing, and whatever else we'll want to share with you 🙂\nAnd most important, feel free to participate in comments or by contacting us directly. We appreciate your feedback!\nWelcome to the Algolia blog!"
  },
  {
    "post_title": "Great discussions at LeWeb'12 London",
    "post_date": "2012-07-03",
    "post_date_timestamp": 1341273600,
    "author_name": "Nicolas Dessaigne",
    "author_image_url": "https://secure.gravatar.com/avatar/785489bc2ac2e08ae66648a8936c1101?s=40&d=mm&r=g",
    "permalink": "https://blog.algolia.com/great-discussions-at-leweb12-london/",
    "image": "https://blog.algolia.com/wp-content/uploads/2014/03/latency-360x200.png",
    "excerpt": "… take long for us to decide it was the way to go, since the perception of speed is so natural that the benefit far outweighs the longer integration code. We'll now work on simplifying it!\nWe'll soon do a post about this demo. In the meantime, stay tuned!\n&nbsp;\n&nbsp;"
  }
]
```

## Create a replica

To run the code examples on this page, [install the latest API client](/doc/libraries/sdk/install).

Create a replica of your `articles` index.
The recommendation is to name your replica indices with a prefix or suffix describing its sorting strategy (for example, `articles_date_desc`).

<Steps>
  <Step title="Create replica">
    [Create a standard or virtual replica](/doc/guides/managing-results/refine-results/sorting/how-to/creating-replicas) (`articles_date_desc`) from the primary index.
    The primary index is likely sorted by relevance but you want to change that for `articles_date_desc`.

    <CodeGroup>
      ```cs C# theme={"system"}
      var response = await client.SetSettingsAsync(
        "INDEX_NAME",
        new IndexSettings { Replicas = new List<string> { "articles_date_desc" } }
      );
      ```

      ```dart Dart theme={"system"}
      final response = await client.setSettings(
        indexName: "INDEX_NAME",
        indexSettings: IndexSettings(
          replicas: [
            "articles_date_desc",
          ],
        ),
      );
      ```

      ```go Go theme={"system"}
      response, err := client.SetSettings(client.NewApiSetSettingsRequest(
        "INDEX_NAME",
        search.NewEmptyIndexSettings().SetReplicas(
          []string{"articles_date_desc"})))
      if err != nil {
        // handle the eventual error
        panic(err)
      }
      ```

      ```java Java theme={"system"}
      UpdatedAtResponse response = client.setSettings(
        "INDEX_NAME",
        new IndexSettings().setReplicas(Arrays.asList("articles_date_desc"))
      );
      ```

      ```js JavaScript theme={"system"}
      const response = await client.setSettings({
        indexName: 'theIndexName',
        indexSettings: { replicas: ['articles_date_desc'] },
      });
      ```

      ```kotlin Kotlin theme={"system"}
      var response =
        client.setSettings(
          indexName = "INDEX_NAME",
          indexSettings = IndexSettings(replicas = listOf("articles_date_desc")),
        )
      ```

      ```php PHP theme={"system"}
      $response = $client->setSettings(
          'INDEX_NAME',
          ['replicas' => [
              'articles_date_desc',
          ],
          ],
      );
      ```

      ```python Python theme={"system"}
      response = client.set_settings(
          index_name="INDEX_NAME",
          index_settings={
              "replicas": [
                  "articles_date_desc",
              ],
          },
      )
      ```

      ```ruby Ruby theme={"system"}
      response = client.set_settings(
        "INDEX_NAME",
        Algolia::Search::IndexSettings.new(replicas: ["articles_date_desc"])
      )
      ```

      ```scala Scala theme={"system"}
      val response = Await.result(
        client.setSettings(
          indexName = "INDEX_NAME",
          indexSettings = IndexSettings(
            replicas = Some(Seq("articles_date_desc"))
          )
        ),
        Duration(100, "sec")
      )
      ```

      ```swift Swift theme={"system"}
      let response = try await client.setSettings(
          indexName: "INDEX_NAME",
          indexSettings: IndexSettings(replicas: ["articles_date_desc"])
      )
      ```
    </CodeGroup>
  </Step>

  <Step title="Sort the records">
    Use the `post_date_timestamp` attribute to sort the `articles_date_desc` virtual index by date in descending order:

    <AccordionGroup>
      <Accordion title="Sort a standard replica">
        <CodeGroup>
          ```cs C# theme={"system"}
          var response = await client.SetSettingsAsync(
            "INDEX_NAME",
            new IndexSettings { Ranking = new List<string> { "desc(post_date_timestamp)" } }
          );
          ```

          ```dart Dart theme={"system"}
          final response = await client.setSettings(
            indexName: "INDEX_NAME",
            indexSettings: IndexSettings(
              ranking: [
                "desc(post_date_timestamp)",
              ],
            ),
          );
          ```

          ```go Go theme={"system"}
          response, err := client.SetSettings(client.NewApiSetSettingsRequest(
            "INDEX_NAME",
            search.NewEmptyIndexSettings().SetRanking(
              []string{"desc(post_date_timestamp)"})))
          if err != nil {
            // handle the eventual error
            panic(err)
          }
          ```

          ```java Java theme={"system"}
          UpdatedAtResponse response = client.setSettings(
            "INDEX_NAME",
            new IndexSettings().setRanking(Arrays.asList("desc(post_date_timestamp)"))
          );
          ```

          ```js JavaScript theme={"system"}
          const response = await client.setSettings({
            indexName: 'theIndexName',
            indexSettings: { ranking: ['desc(post_date_timestamp)'] },
          });
          ```

          ```kotlin Kotlin theme={"system"}
          var response =
            client.setSettings(
              indexName = "INDEX_NAME",
              indexSettings = IndexSettings(ranking = listOf("desc(post_date_timestamp)")),
            )
          ```

          ```php PHP theme={"system"}
          $response = $client->setSettings(
              'INDEX_NAME',
              ['ranking' => [
                  'desc(post_date_timestamp)',
              ],
              ],
          );
          ```

          ```python Python theme={"system"}
          response = client.set_settings(
              index_name="INDEX_NAME",
              index_settings={
                  "ranking": [
                      "desc(post_date_timestamp)",
                  ],
              },
          )
          ```

          ```ruby Ruby theme={"system"}
          response = client.set_settings(
            "INDEX_NAME",
            Algolia::Search::IndexSettings.new(ranking: ["desc(post_date_timestamp)"])
          )
          ```

          ```scala Scala theme={"system"}
          val response = Await.result(
            client.setSettings(
              indexName = "INDEX_NAME",
              indexSettings = IndexSettings(
                ranking = Some(Seq("desc(post_date_timestamp)"))
              )
            ),
            Duration(100, "sec")
          )
          ```

          ```swift Swift theme={"system"}
          let response = try await client.setSettings(
              indexName: "INDEX_NAME",
              indexSettings: IndexSettings(ranking: ["desc(post_date_timestamp)"])
          )
          ```
        </CodeGroup>
      </Accordion>

      <Accordion title="Sort a virtual replica">
        <CodeGroup>
          ```cs C# theme={"system"}
          var response = await client.SetSettingsAsync(
            "INDEX_NAME",
            new IndexSettings { CustomRanking = new List<string> { "desc(post_date_timestamp)" } }
          );
          ```

          ```dart Dart theme={"system"}
          final response = await client.setSettings(
            indexName: "INDEX_NAME",
            indexSettings: IndexSettings(
              customRanking: [
                "desc(post_date_timestamp)",
              ],
            ),
          );
          ```

          ```go Go theme={"system"}
          response, err := client.SetSettings(client.NewApiSetSettingsRequest(
            "INDEX_NAME",
            search.NewEmptyIndexSettings().SetCustomRanking(
              []string{"desc(post_date_timestamp)"})))
          if err != nil {
            // handle the eventual error
            panic(err)
          }
          ```

          ```java Java theme={"system"}
          UpdatedAtResponse response = client.setSettings(
            "INDEX_NAME",
            new IndexSettings().setCustomRanking(Arrays.asList("desc(post_date_timestamp)"))
          );
          ```

          ```js JavaScript theme={"system"}
          const response = await client.setSettings({
            indexName: 'theIndexName',
            indexSettings: { customRanking: ['desc(post_date_timestamp)'] },
          });
          ```

          ```kotlin Kotlin theme={"system"}
          var response =
            client.setSettings(
              indexName = "INDEX_NAME",
              indexSettings = IndexSettings(customRanking = listOf("desc(post_date_timestamp)")),
            )
          ```

          ```php PHP theme={"system"}
          $response = $client->setSettings(
              'INDEX_NAME',
              ['customRanking' => [
                  'desc(post_date_timestamp)',
              ],
              ],
          );
          ```

          ```python Python theme={"system"}
          response = client.set_settings(
              index_name="INDEX_NAME",
              index_settings={
                  "customRanking": [
                      "desc(post_date_timestamp)",
                  ],
              },
          )
          ```

          ```ruby Ruby theme={"system"}
          response = client.set_settings(
            "INDEX_NAME",
            Algolia::Search::IndexSettings.new(custom_ranking: ["desc(post_date_timestamp)"])
          )
          ```

          ```scala Scala theme={"system"}
          val response = Await.result(
            client.setSettings(
              indexName = "INDEX_NAME",
              indexSettings = IndexSettings(
                customRanking = Some(Seq("desc(post_date_timestamp)"))
              )
            ),
            Duration(100, "sec")
          )
          ```

          ```swift Swift theme={"system"}
          let response = try await client.setSettings(
              indexName: "INDEX_NAME",
              indexSettings: IndexSettings(customRanking: ["desc(post_date_timestamp)"])
          )
          ```
        </CodeGroup>
      </Accordion>
    </AccordionGroup>
  </Step>
</Steps>
