Issue with Sorting French Dates in DataTables

Issue with Sorting French Dates in DataTables

Thomas91200Thomas91200 Posts: 1Questions: 0Answers: 0

Hello everyone,

Description of problem:
I'm working on a React application using DataTables to display data. I'm using two additional plugins: one for French language support and another for date sorting (ultimate-datetime-sorting). The problem is that date sorting works perfectly in English, but I'm having trouble sorting dates correctly when they are in French.

The dates are not sorting correctly when displayed in French. Everything works fine in English. I tried using moment.js to set the locale to French and a sorting plugin, but the issue persists.

Here's a snippet of my code:

import moment from "moment";
import "moment/locale/fr";

// Function to translate English months to French
export function translateFrenchMonth(dateStr) {
  const translatedMonths = {
    Jan: "Janv",
    Fev: "Févr",
    Mars: "Mars",
    Avr: "Avr",
    Mai: "Mai",
    Juin: "Juin",
    Juil: "Juil",
    Aout: "Août",
    Sept: "Sept",
    Oct: "Oct",
    Nov: "Nov",
    Dec: "Déc",
  };

  const translatedDateStr = dateStr.replace(
    /(Jan|Fev|Mars|Avr|Mai|Juin|Juil|Aout|Sept|Oct|Nov|Dec)/g,
    (match) => translatedMonths[match]
  );

  return translatedDateStr;
}

export function updateDateFormat(data) {
  return data?.map((item) => {
    const tm = translateFrenchMonth(item.timestamp);
    const timestamp = item?.timestamp && moment(tm, userTimeFormat);

    return {
      ...item,
      timestamp,
    };
  });
}

const userLanguage = baja.getLanguage();
if (userLanguage === "en") {
  moment.locale("en");
} else {
  moment.locale("fr");
}

const columnDefs = [
  {
    language: userLanguage,
    type: "date",
    targets: 0,
    render: function (data) {
      return moment(data).local().format(userTimeFormat);
    },
  },
];

// Applying translated date format
const dataTable = utils.updateDateFormat(data);

<StyledDataTable
  ...
  data={dataTable}
  columnDefs={columnDefs}
/>

Question: How can I fix this issue with sorting dates in French? Is there a better approach to handling multilingual date formats and sorting with DataTables and React?

Thank you in advance for your help!

Replies

  • allanallan Posts: 63,441Questions: 1Answers: 10,459 Site admin

    There should be no need for the "ultimate" date time sorting plugin any more. DataTables has all of those abilities built in (although you still do need Moment or Luxon).

    The DateTime abilities in DataTables done in part with DataTable.datetime(), and in part with the datetime renderer. The best way to handle what you are looking for will depend on the format of the data in {dataTable}. Can you show me that please?

    This group of examples might also be of some interest.

    Allan

Sign In or Register to comment.