So I'm getting some dates from my backend.
I only need the date (without the time) and the format should be relative to the user's browser settings.
I've chosen this approach:
function dateFormatter(params) {
if (!params.value || params.value == 'None') return ''
return new Date(params.value).toLocaleString(undefined, options = { year: 'numeric', month: 'numeric', day: '2-digit' });
}
So far so good. It is working fine. Passing undefined as the first parameter makes it take whatever locale the user's using.
The problem is that now, for those strings returned by this function, I need a comparator. Something like this:
filterParams: {
// provide comparator function
comparator: (filterLocalDateAtMidnight, cellValue) => {
const dateAsString = cellValue;
if (dateAsString == null) {
return 0;
}
// In the example application, dates are stored as dd/mm/yyyy
// We create a Date object for comparison against the filter date
const dateParts = dateAsString.split('/');
const day = Number(dateParts[2]);
const month = Number(dateParts[1]) - 1;
const year = Number(dateParts[0]);
const cellDate = new Date(year, month, day);
// Now that both parameters are Date objects, we can compare
if (cellDate < filterLocalDateAtMidnight) {
return -1;
} else if (cellDate > filterLocalDateAtMidnight) {
return 1;
}
return 0;
}
How can I implement this comparator? Because my date format is dynamic according to the user, I can't just split dateParts[] like this example does.
Thanks.