Search code examples
vue.jsvuejs2momentjsvue-tables-2

Make datetime column sortable in Vue Tables 2


I have a custom component that is using the v-client-table method from the Vue Tables 2. The table has two columns, one of which is a datetime column (format: MM/DD/YYYY h:mm A). I have it as sortable, but it doesn't sort accurately based on the time. The output of that appears like this:

table output example

As you can see, it goes from 12:09 PM to 12:30 AM. Unfortunately, this date/time format is required.

Question: is there a way to incorporate momentjs into the configuration to make this properly sort (without using a filter as it shows in the client-side-sorting documentation)?

Below is the data and options:

export const content = {
    state: {
        columns: ['callDateTime', 'explanation'],
        tableData: [
            { callDateTime: '10/13/2017 10:09 AM', explanation: "Lorem ipsum dolor sit amet, consectetur adipiscing elit." },
            { callDateTime: '10/13/2017 12:30 AM', explanation: "Lorem ipsum dolor" },
            { callDateTime: '10/13/2017 12:09 PM', explanation: "Lorem ipsum dolor sit amet },
            { callDateTime: '10/13/2017 1:15 PM', explanation: "Ut a fringilla mauris" },
            { callDateTime: '10/13/2017 1:30 PM', explanation: "Lorem ipsum dolor" }
        ],
        options: {
            headings: {
                'callDateTime': 'Call Date/Time',
                'explanation': 'Interaction Notes',
            },
            filterable: 'false',
            sortable: 'callDateTime',                           
            orderBy: { column: 'callDateTime' },
            pagination: {
                edge: false,
                dropdown: false,
                chunk: 1
            },
            sortIcon: {
                down: 'arrow arrow-down',
                up: 'arrow arrow-up'
            },
            perPage: '10',
            texts: {
                count: ''                                       
            }
        }
    }
}

Solution

  • Use can use customSorting for this

    customSorting: {
        callDateTime: function (ascending) {
            return function (a, b) {
                let dateA = new Date(a.callDateTime);
                let dateB = new Date(b.callDateTime);
    
                if (ascending)
                    return dateA >= dateB ? 1 : -1;
    
                return dateA <= dateB ? 1 : -1;
            }
        }
    }