datetime field is sorted as string

datetime field is sorted as string

the_codeholicthe_codeholic Posts: 1Questions: 1Answers: 0

I have a Datatble for my Django web app, the backend sends the date for the field updated as 'Feb. 14, 2023, 3:58 p.m.'. when I use the sorting feature, it always sorts in 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 datable jquery documentation and some StackOverflow answers but it didn't give me the desired output.

I tried this code

$("#progress").DataTable({
        columnDefs: [
            {
                targets: [0],
                type: 'datetime-locale',
                orderable: true
            }
        ]
    });

but it still doesn't sorted well, it sorted like this -> Feb. 24, 2023, 9:57 a.m. , Feb. 14, 2023, 4:26 p.m. , Feb. 14, 2023, 3:58 p.m. , April 24, 2023, 10:04 a.m.

Answers

  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin

    type: 'datetime-locale',

    Remove that - if DataTables' type detection doesn't match against the format, then forcing it to a specific type won't work.

    This is the example you want to make your table sort as expected. You need to use the DataTable.datetime() method to register a date / time format with DataTables. It will then be able to automatically detect and sort that type.

    Allan

Sign In or Register to comment.