How do I filter date range in DataTables?
Here is DataTable
with Single DatePicker
as "from" Date Filter
LiveDemo
Here is DataTable
with Two DatePickers
for DateRange (To and From) Filter
LiveDemo
Here is my solution, cobbled together from the range filter example in the datatables docs, and letting moment.js do the dirty work of comparing the dates.
HTML
<input
type="text"
id="min-date"
class="date-range-filter"
placeholder="From: yyyy-mm-dd">
<input
type="text"
id="max-date"
class="date-range-filter"
placeholder="To: yyyy-mm-dd">
<table id="my-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Created At</th>
</tr>
</thead>
</table>
JS
Install Moment: npm install moment
// Assign moment to global namespace
window.moment = require('moment');
// Set up your table
table = $('#my-table').DataTable({
// ... do your thing here.
});
// Extend dataTables search
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var min = $('#min-date').val();
var max = $('#max-date').val();
var createdAt = data[2] || 0; // Our date column in the table
if (
( min == "" || max == "" )
||
( moment(createdAt).isSameOrAfter(min) && moment(createdAt).isSameOrBefore(max) )
)
{
return true;
}
return false;
}
);
// Re-draw the table when the a date range filter changes
$('.date-range-filter').change( function() {
table.draw();
} );
JSFiddle Here
Notes
- Using moment decouples the date comparison logic, and makes it easy to work with different formats. In my table, I used
yyyy-mm-dd
, but you could usemm/dd/yyyy
as well. Be sure to reference moment's docs when parsing other formats, as you may need to modify what method you use.
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var FilterStart = $('#filter_From').val();
var FilterEnd = $('#filter_To').val();
var DataTableStart = data[4].trim();
var DataTableEnd = data[5].trim();
if (FilterStart == '' || FilterEnd == '') {
return true;
}
if (DataTableStart >= FilterStart && DataTableEnd <= FilterEnd)
{
return true;
}
else {
return false;
}
});
--------------------------
$('#filter_From').change(function (e) {
Table.draw();
});
$('#filter_To').change(function (e) {
Table.draw();
});