此代码仅用于比较日期。我也希望比较时间。有人可以针对角度8解给出正确的解决方案吗?
{headerName: 'Start Date', field: 'CreatedDate', sortable:true,
cellRenderer: (data) => {
return data.value ? (new Date(data.value)).toLocaleDateString() : '';
}, comparator: dateComparator}
function dateComparator(date1, date2) {
var date1Number = monthToComparableNumber(date1);
var date2Number = monthToComparableNumber(date2);
if (date1Number === null && date2Number === null) {
return 0;
}
if (date1Number === null) {
return -1;
}
if (date2Number === null) {
return 1;
}
return date1Number - date2Number;
}
function monthToComparableNumber(date) {
if (date === undefined || date === null || date.length !== 10) {
return null;
}
var yearNumber = date.substring(6, 10);
var monthNumber = date.substring(3, 5);
var dayNumber = date.substring(0, 2);
var result = yearNumber * 10000 + monthNumber * 100 + dayNumber;
return result;
}
答案 0 :(得分:4)
function dateComparator(date1, date2) {
var date1Number = date1 && new Date(date1).getTime();
var date2Number = date2 && new Date(date2).getTime();
if (date1Number == null && date2Number == null) {
return 0;
}
if (date1Number == null) {
return -1;
} else if (date2Number == null) {
return 1;
}
return date1Number - date2Number;
}
因为date1Number == null
还会检查undefined
,所以我将使用双精度等于而不是三等于。