Mil*_*los 3 arrays date typescript react-typescript
我有一个带有这样日期的对象
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",
};
Run Code Online (Sandbox Code Playgroud)
我用它创建了一个数组,其中的日期如下
const arrayOfDates: Date[] = Object.values(dateObject).map(
(date: string | unknown) => new Date(date as string)
);
Run Code Online (Sandbox Code Playgroud)
我正在尝试从该数组中获取最小和最大日期,如下所示
const minDate = new Date(Math.min.apply(null, arrayOfDates));
const maxDate = new Date(Math.max.apply(null, arrayOfDates));
Run Code Online (Sandbox Code Playgroud)
arrayOfDates但我在Math.min 和 Math.max 内部收到打字稿错误。错误是这样说的Argument of type 'Date[]' is not assignable to parameter of type 'number[]'. Type 'Date' is not assignable to type 'number'.ts(2345)。我究竟做错了什么?
对于您的问题,有一个比您提供的答案更简单的解决方案。问题是 Math.min 和 Math.max 函数尝试查找最小/最大数字,并且不知道如何比较日期。如果您的数组是数字数组,那么它就会起作用。您可以使用 Date's 获取一个数字.getTime(),它会给出自 1970 年 1 月 1 日(== UNIX 时间)以来的毫秒数。Date 构造函数也接受该数字作为输入,并将根据该数字创建一个 Date 对象。
我还更改了代码中的一些内容,我认为这会让代码更干净。
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));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1289 次 |
| 最近记录: |