ultimate date sorting blog + questions, observations

ultimate date sorting blog + questions, observations

rldean1rldean1 Posts: 141Questions: 66Answers: 1

Observations:

  • These are for detection only to facilitate sorting: $.fn.dataTable.moment("MM-DD-YYYY");, and $.fn.dataTable.moment("YYYY-MM-DDTHH:mm:ss");
  • The render function and moment.js can be used to format your date:
render: function (data, type, row) {
    return moment(data).format('MM-DD-YYYY');
}

Situation:

If my date is a raw time stamp, and my declaration is: $.fn.dataTable.moment("YYYY-MM-DDTHH:mm:ss");,

BUT, I'm rendering the date like this: return moment(data).format('MM-DD-YYYY');,

THEN It won't sort. I must detect it like this: $.fn.dataTable.moment("MM-DD-YYYY"); instead.

HOWEVER, upon a <tr> click, the date is still the raw datestamp -- the original data, which is fine.

Questions:

What is the best date format to send to DT? Should I send back a raw datetime? Or, should I format it the way I want it on the backend?

It seems like $.fn.dataTable.moment is looking at rendered data. What's the difference between the raw data and the rendered data, in this scenario?

If I don't need to worry about it, just tell me to stop.

Replies

  • allanallan Posts: 61,652Questions: 1Answers: 10,094 Site admin

    You need to use orthogonal data. Specifically render the data for human reading only when the data type requested in the rendering function is display or filter.

    This plug-in can be useful - its basically the inverse of the sorting plug-in.

    Allan

  • rldean1rldean1 Posts: 141Questions: 66Answers: 1

    @allan ,

    Heck yeah!!!! That did it!! Both plugins worked too: datetime-moment.js, and datetime.js. Definitely had to render appropriately as stated -- orthogonal data.

    Here's some code, just for posterity:

    If your datestamp looks like this 1998-07-01T00:00:00, you could do this:

    datetime.js plugin

    columns: [
        {
            data: 'EffectDate',
            title: 'Effective Date',
            render: $.fn.dataTable.render.moment("YYYY-MM-DDTHH:mm:ss", "MM-DD-YYYY"),
        }
    ]
    

    datetime-moment.js plugin

              //register the date/time format(s) that you wish DataTables to detect
              $.fn.dataTable.moment("YYYY-MM-DDTHH:mm:ss");
    
    columns: [
        {
            data: 'EffectDate',
            title: 'Effective Date',
            render: function (data, type, row) {
    
                if (type === 'display' || type === 'filter') {
    
                    return moment(data).format('MM-DD-YYYY');
    
                } else {
    
                    return data;
                }
    
            }
        }
    ]
    
This discussion has been closed.