我正在嘗試爲dataTables開發自定義日期範圍過濾器。用戶可以在兩個輸入中輸入開始日期和結束日期,並過濾整個表格。在JavaScript中比較新日期失敗
輸入開始日期和結束日期時,結果相符。當我只輸入其中一個時,結果失敗。例如;起始日期是2017年12月1日,但我可以看到實例與日期29-11-2016 ...我的過濾代碼:
$('#filter').on('click', function(e) {
e.preventDefault();
var startDate = $('#start').val(),
endDate = $('#end').val();
filterByDate(10, startDate, endDate); // We call our filter function
$dTable.dataTable().fnDraw(); // Manually redraw the table after filtering
});
var filterByDate = function(column, startDate, endDate) {
$.fn.dataTableExt.afnFiltering.push(
function(oSettings, aData, iDataIndex) {
var rowDate = normalizeDate(aData[10]),
start = normalizeDate(startDate),
end = normalizeDate(endDate);
// If our date from the row is between the start and end
if (start <= rowDate && rowDate <= end) {
console.log(start <= rowDate);
return true;
} else if (rowDate >= start && end === '' && start !== ''){
console.log(rowDate >= start && end === '' && start !== '');
return true;
} else if (rowDate <= end && start === '' && end !== ''){
return true;
} else {
return false;
}
}
);
};
var normalizeDate = function(dateString) {
var date = new Date(dateString);
var normalized = ("0" + date.getDate()).slice(-2) + '/'+ (("0" + (date.getMonth() + 1)).slice(-2)) + '/' +date.getFullYear() ;
return normalized;
};
可能一些JavaScript天才幫助我獲得的rowData >= start....
比較和rowDate <= end....
工作正常嗎?輸入日期由/
分隔,在我的表格中由/
分隔,但normalizeData函數使它們具有相同的佈局。
什麼是* dateString *的價值?在使用Date構造函數解析字符串之前,請考慮[*爲什麼Date.parse會給出不正確的結果*](http://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results)。 – RobG