I have a v-data-table which includes dates that have been formatted with dayjs to "MM/DD/YYYY" however some dates are null since they have not been completed yet. I am trying to add sorting in the header array for this formatted date column by:
{ title: 'Memo Date', key: 'memo_date', align: 'center', visible: true, filtered: [], sort:
function(a: string, b: string) {
if (a == null && b == null)
{
let c = dayjs().format("MM/DD/YYYY")
console.log(c)
return 0
}
else if (a == null) {
let c = dayjs().format("MM/DD/YYYY")
console.log(c)
return (dayjs(c).diff(dayjs(b)))
} else if (b == null)
{
let c = dayjs().format("MM/DD/YYY")
console.log(c)
return (dayjs(a).diff(dayjs(c)))
}
return dayjs(a).diff(dayjs(b))
}
},
However, the ordering does not seem to put these null dates as the most recent date to sort ahead of the actually dates. For instance, if the date is null i try to convert it to today so it is ordered as the newest item but this does not seem to work as expected.
UPDATE:
Based on the recent answer I have posted a potential usage for sorting but still the null dates are showing up as earlier dates whereas I want those to be considered the newest dates:
const customDateSort = (a : string, b : string) => {
const aDate = String((new Date(a)).getTime())
const bDate = String((new Date(b)).getTime())
return aDate.localeCompare(bDate)
}
2
Answers
If you want to compare Dates, you can convert them to epoch timestamps aka the time elapsed since January 1, 1970, UTC.
The lower the number, the older it is. Simplest way to sort them I think.
Here is a decent article on the subject.
Otherwise, Temporal API probably has some functions for that use-case. Or using any kind of date library should have such a feature too, but using a vanilla JS solution is always nice.
To filter on the array to convert into current time if
null
, then sort properly each timestampThis may be a problem with how the comparator function works. It seems that you are also trying to sort dates in descending order by default as well which can be a bit confusing to put into code.
take for example
today.diff(yesterday)
will return a positive integer, which sortstoday
afteryesterday
(yesterday
is on top)To solve this, I think you should try reversing your
.diff()
order: