DataTables with momentjs - How to use fromNow() function
DataTables with momentjs - How to use fromNow() function
Hi,
I'm trying to use momentjs with DataTables based on this blog post (http://datatables.net/blog/2014-12-18).
I have a column with "Last Update" and want to see the fromNow() function of momentjs lib.
So "3 days ago" or "7 hours ago".
I tried to write a new render function in DataTables like this:
"render": function (data, type, row) {
return moment(data, IN_DATE_TIME_FORMAT).fromNow();
}
... and it works! But sorting does not work properly. "3 days ago" comes before of "7 hours ago" (sort by most recent).
Seems that DT still checks for strings and not for timestamps while sorting.
Why? And even better, how can I fix?
Thanks for your advice.
This question has an accepted answers - jump to answer
Answers
You could try this approach:
https://datatables.net/forums/discussion/29812/custom-sorting-with-heavely-formated-date
Also, can you link to the page so we can take a look and see what is going wrong please.
Interesting question on expected behavior - should DT sort on the data value or the rendered value?
You may need a separate column with a numeric value that sorts correctly and then use the orderData property of the column definition so that the human friendly column references the hidden column for sorting.
https://datatables.net/reference/option/columns.orderData
I already gave a working example.
The rendered value - this is how orthogonal data is implemented. You can return or use different data points for each data type DataTables needs.
Having said that, sorting plug-ins can be used to "de-format" the displayed value if you are not using orthogonal data.
Allan