Home > front end >  React AG Grid custom sort for date and time using format MM/DD/YYYY ##:##AM or PM
React AG Grid custom sort for date and time using format MM/DD/YYYY ##:##AM or PM

Time:09-23

Using React AG Grid I am trying to sort in descending order the by date and time. Example data below. Setting sortable to true sorts the dates correctly but not the time.

10/31/2022  8:00AM
12/31/2022  4:59PM
12/12/2022  3:00PM
10/31/2022  7:00PM
10/31/2022  7:00AM

CodePudding user response:

Hi to compare these dates, you need to provide a comparator in the column definition, and then the grid will know how to sort the column with the data you mentioned.

  const [columnDefs] = useState([
    ...
    { field: 'date', comparator: dateComparator, sort: 'desc' },
    ...
  ]);

For the example data, you provided, first convert it to a number.

// eg 08/29/2004 4:59PM gets converted to 20040829.1659
const monthToComparableNumber = (date) => {
  if (date === undefined || date === null || date.length !== 18) {
    return null;
  }

  const last = date.length;

  const yearNumber = Number.parseInt(date.substring(6, 10));
  const dayNumber = Number.parseInt(date.substring(3, 5));
  const monthNumber = Number.parseInt(date.substring(0, 2));

  const partOfDay = date.substring(last - 2, last) == 'PM' ? 0.12 : 0;
  const strHour = String(Number(date.substring(last - 7, last - 5)));

  const hour =
    strHour.length == 2 ? Number('0.'   strHour) : Number('0.0'   strHour);
  const h24 = partOfDay   hour;

  const minutes = Number('0.00'   date.substring(last - 4, last - 2));

  return yearNumber * 10000   monthNumber * 100   dayNumber   h24   minutes;
};

You can use the monthToComparableNumber() in the comparator function.

const dateComparator = (date1, date2) => {
  const date1Number = monthToComparableNumber(date1);
  const date2Number = monthToComparableNumber(date2);
  if (date1Number === null && date2Number === null) {
    return 0;
  }
  if (date1Number === null) {
    return -1;
  }
  if (date2Number === null) {
    return 1;
  }
  return date1Number - date2Number;
}; 

I made an AG Grid React example in plunker with your example data. the code from above is used in the example below: https://plnkr.co/edit/f25Bgp9a34vpbbTT?open=index.jsx

  • Related