0

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

2
  • 1
    Hi, and welcome to SFSE! (a) please don't use screenshots to display code. The {} button in the editor will format your code in a code block nicely. (b) What format are your dates in?
    – sfdcfox
    Jul 29 '20 at 4:39
  • The format of Dates is DD MMM YYYY. For example : 22 Jul 2020. I tried by updating the format to DD/MM/YYYY (22/07/2020) too, but the behaviour is same in that case too. Jul 29 '20 at 5:23
2

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.

1
0

I came across this same issue today. What helped me was using the fieldName param we get from the column click event, looking through the table column header array, and getting the field type.

var fieldType;
 for(var i = 0; i < tableColumns.length; i++){              
     if(tableColumns[i].fieldName == fieldtoSort){
         fieldType = tableColumns[i].type;
         break;
     }
 }

From there if it's a "date" we can convert it to something that's sortable and use the regular sort from the salesforce example.

var rowAColValue = new Date(rowAColValue);
var rowBColValue = new Date(rowBColValue);

This should work in AURA too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.