DataTables with momentjs - How to use fromNow() function

DataTables with momentjs - How to use fromNow() function

anueliconanuelicon Posts: 5Questions: 1Answers: 0

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

  • tangerinetangerine Posts: 3,350Questions: 37Answers: 394
    Answer ✓
  • allanallan Posts: 61,824Questions: 1Answers: 10,130 Site admin

    Also, can you link to the page so we can take a look and see what is going wrong please.

  • ThomDThomD Posts: 334Questions: 11Answers: 43

    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

  • tangerinetangerine Posts: 3,350Questions: 37Answers: 394

    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.

    I already gave a working example.

  • allanallan Posts: 61,824Questions: 1Answers: 10,130 Site admin

    Interesting question on expected behavior - should DT sort on the data value or the rendered value?

    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

This discussion has been closed.