Need Help with date sorting
Need Help with date sorting
Noodles12
Posts: 113Questions: 41Answers: 2
I am using a datatable that has date column. I am trying to sort is by Date Ascending but it doesn't seem to work. It is not sorting properly. It places July 30 above Mar 5. Can you please help. Thanks. Here is my code -
<table class="row-border stripe dt-right dataTable no-footer dtr-inline" id="test" style="width: 100%;"><thead text-align="left"><tr><th>Event</th><th>City, State</th><th>Date</th></tr></thead>
<tbody>
<tr>
<td>My first event</th>
<td>Devnver,CO</th>
<td>Mar 4 - 7, 2024</th>
</tr>
<tr>
<td>My third event</th>
<td>Devnver,CO</th>
<td>Mar 5, 2024</th>
</tr>
<tr>
<td>My second event</th>
<td>Devnver,CO</th>
<td>Jul 30 - 31, 2024</th>
</tr>
<tr>
<td>My fourth event</th>
<td>Devnver,CO</th>
<td>Mar 5, 2024</th>
</tr>
$(document).ready(function() {
$.fn.dataTable.moment( 'MM/DD/YYYY' );
$('#test').DataTable({
responsive: true,
paging: false,
lengthChange: false,
fixedHeader: true,
columnDefs: [
{
targets: 2,
type: 'date',
}
],
order:[[ 2, 'asc' ]]
} );
} );
This question has an accepted answers - jump to answer
Answers
The first question is how do you want
Mar 4 - 7, 2024
sorted againstMar 5, 2024
?Assuming you want to sort against the first date in the range you could use Orthogonal data to remove the range for the
sort
operation usingcolumns.render
. For exampleMar 4 - 7, 2024
would beMar 4 , 2024
.Use
DataTable.datetime()
to set the proper date format depending on the library you are using. For example.For further help please build a test case and provide exactly how the dates and date ranges should be sorted.
https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case
Kevin
Thankyou, please see my testcase here -
https://live.datatables.net/xizazebo/1/edit
Yes, I want Mar 4 - 7, 2024 sorted against Mar 5, 2024.
Is this what you are looking for?
https://live.datatables.net/ceriruvu/1/edit
It replaces the date range, ie
4 - 7
, with the first date, ie4
via regex replace for thesort
andtype
detection. I added moment.js like the example I linked to. You don't want to usecolumns.type
for this case and let the auto detection match the format specified inDataTable.datetime('MMM D, YYYY');
.Kevin
Yes, thankyou!