To use the comparedesc
function from the date-fns
library in TypeScript, follow the steps below:
date-fns
library using npm
or yarn
:21 chars2 lines
or
18 chars2 lines
comparedesc
function in your TypeScript file:index.ts40 chars2 lines
comparedesc
function in your code to compare two dates in descending order:index.ts72 chars2 lines
The comparedesc
function returns a number that indicates the order of the two dates. If the first date is greater than the second date, it returns -1
. If the first date is less than the second date, it returns 1
. If the two dates are equal, it returns 0
.
You can use the result of the comparedesc
function to sort an array of dates in descending order, for example:
index.ts236 chars10 lines
In this example, the dates
array is sorted in descending order using the comparedesc
function. The result is [2021-10-01T04:00:00.000Z, 2021-05-01T04:00:00.000Z, 2021-01-01T05:00:00.000Z]
, which is the order of the dates from latest to earliest.
gistlibby LogSnag