Search code examples
jquerydjangodatatable

Datatble datetime field is sorted as string


I have a Datatble for my django web app, the backend sends date for the field updated as 'Feb. 14, 2023, 3:58 p.m.'. when I use the sorting feature, it always sorts as alphabetical order, where 'April 24, 2023, 10:04 a.m.' comes before Feb because A is bigger than F in alphabetical order, so how to solve this? I tries some from datatble jquery documentation and some StackOverflow answers but it didn't gave me the desired output


Solution

  • after jquery importing, import momentjs

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    

    and add this script

    <script type="text/javascript">
        $("#datatble_id").DataTable({
            columnDefs: [
                {
                    targets: [0], // your field position
                    type: 'datetime',
                    render: function (data, type, row, meta) {
                        var momentObj = moment(data, 'MMM. DD, YYYY, h:mm a');
                        if (type === 'sort') {
                            return momentObj.unix();
                        }
                        return momentObj.format('MMM. DD, YYYY, h:mm a');
                    },
                    orderable: true
                }
            ]
        });
    </script>