I have an object with dates like this
const dateObject = {
"BaseTransactions.maxOccurredAt": "2021-01-19T20:30:45.000",
"BaseTransactions.minOccurredAt": "2016-12-28T12:55:37.000",
"EmailCampaignEvents.maxOccurredAt": "2021-04-13T11:32:50.000",
"EmailCampaignEvents.minOccurredAt": "2021-04-09T12:15:26.000",
};
and I've created an array from it with dates like this
const arrayOfDates: Date[] = Object.values(dateObject).map(
(date: string | unknown) => new Date(date as string)
);
and I'm trying to get the min and max dates from that array like this
const minDate = new Date(Math.min.apply(null, arrayOfDates));
const maxDate = new Date(Math.max.apply(null, arrayOfDates));
but I am getting an typescript error for arrayOfDates
inside of Math.min and Math.max. The error says this Argument of type 'Date[]' is not assignable to parameter of type 'number[]'. Type 'Date' is not assignable to type 'number'.ts(2345)
.
What am I doing wrong?
There's a much simpler solution to your issue than the answer you provided. The issue is that the Math.min and Math.max functions tries to find the smallest/biggest number, and doesn't know how to compare dates. If your array instead was an array of numbers, it would have worked. You can get a number by using Date's .getTime()
which will give you the number of milliseconds since Jan 1 1970 (== UNIX time). The Date constructor also accepts that as input, and will create a Date object from that number.
I also changed some things in your code which I thought would make it cleaner.
const arrayOfDateNumbers: number[] = Object.values(dateObject)
.map(date =>
(new Date(date)).getTime()
);
const minDate = new Date(Math.min(...arrayOfDateNumbers));
const maxDate = new Date(Math.max(...arrayOfDateNumbers));