[SalesForce] Sorting on Date field in lightning data table is only sorting with Day not with Day month and year(complete Date value) in LWC

Hi I have a lightning data table in which sorting on Date field is only sorting with 'Day' not with Day month and year(complete Date value) in LWC.

Lightning Data Table :

enter image description here

Code I am using for sorting :

enter image description here

Can anybody please help on getting it sorted with full date value

Best Answer

When parsing dates, you should format them in ISO-8601 format (YYYY-MM-DD). This would allow proper sorting. Here's a modification you could do:

sortData(fieldName, sortDirection) {
  let sortResult = [...this.data]; // Same as Object.assign([], this.data)
  let parser = (v) => v;
  let column = this.columns.find(c=>c.fieldName===fieldName);
  if(column.type==='date' || column.type==='datetime') {
    parser = (v) => (v && new Date(v));
  }
  let sortMult = sortDirection === 'asc'? 1: -1;
  this.data = sortResult.sort((a,b) => {
    let a1 = parser(a[fieldName]), b1 = parser(b[fieldName]);
    let r1 = a1 < b1, r2 = a1 === b1;
    return r2? 0: r1? -sortMult: sortMult;
  });
}

This extra parsing step converts dates (particularly dates that were in locale format) to a proper date, allowing proper sorting.

Related Topic