I want to sort date column in gridjs and i am displaying date in mm/dd/yyyy format

365 Views Asked by At

I want to sort date column in gridjs and i am displaying it in mm/dd/yyyy format. Currently it is taking as string and sorting incorrectly. Any formatter or sort option available for date column in girdjs? No solution till now

1

There are 1 best solutions below

0
Daniel S On

I had the same problem. The date from an API was in RFC3339 format, and i wanted to output german format while maintaining sorting ability.

I used a combination of a custom sorter and a custom formatter.

Here is my formatting function:

dateFormatter = function(date) {
    if (date) {
        const dateObj = new Date(date);
        return dateObj.toLocaleString('de-DE', {
            timeZone: 'Europe/Berlin',
            /*weekday: "long",*/
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
        });
    }
    return '';
};

I converted it with the help of toLocaleString (adjust to your needs).

My comparing function is pretty simple:

compare: (a, b) => {
    return new Date(b) < new Date(a);
}

With gridjs, you can use both functions as noted here:

const gridJsConfig = Object.assign(window.gridJsDefaults, {
        columns: [
            // ...
            {
                id: 'registrationNumberValidTo',
                formatter: dateFormatter,
                sort: {
                    compare: (a, b) => {
                        return new Date(b) < new Date(a);
                    }
                }
            },
            
        },
        server: {
            // ....
        }
    });