skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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>
    

  2. Use this postgres Code.

    use dummy table as

    create table test (
      datex text
    )
    

    Insert data

    insert into test (datex) values ('Feb. 14, 2023, 3:58 p.m.');
    insert into test (datex) values ('April 24, 2023, 10:04 a.m.');
    
    
    select * ,
    split_part(datex, ' ', 1),--get Month string
    rtrim(split_part(datex, ' ', 2),','),--get day string
    rtrim(split_part(datex, ' ', 3),','),--get year string
    EXTRACT(MONTH FROM TO_DATE(split_part(datex, ' ', 1), 'Mon')),--convert month into number
    (rtrim(split_part(datex, ' ', 3),',')||'-'||TO_CHAR(EXTRACT(MONTH FROM TO_DATE(split_part(datex, ' ', 1), 'Mon')), 'fm00')||'-'||rtrim(split_part(datex, ' ', 2),','))::date as newdat
    from test order by newdat
    

    I split the string using the "split part" function, then converted into the date column.

    After that use "order by" to sort the date column.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search