查找 min/max 两个日期(键入)
Find min/max of two dates (typed)
我想要强类型代码。当我应用类似问题的解决方案时 - Min/Max of dates in an array? - 我收到错误
TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.
我的代码
const min: Date = Math.min(begin as Date, (end || defaultDate) as Date);
const max: Date = Math.max(begin as Date, (end || defaultDate) as Date);
begin as Date
部分有下划线。
在 Typescript 中查找 min/max 日期的正确方法是什么?
您可以在打字稿中像这样比较日期:
const begin: Date = new Date();
const end: Date = new Date();
const min: Date = begin < end ? begin : end;
const max: Date = begin > end ? begin : end;
您遇到的问题是 Math.min
returns 一个数字。
假设您有一个数组,您将通过获取其 getTime()
来映射日期部分,然后将其传递给 Math.min
,当您取回它时,再次将其转换为日期。
const result:number[] = array.map((item)=>new Date(item.date).getTime());
console.log(new Date(Math.min(...result)));
感谢@OliverRadini 提供示例代码!
我自己的解决方案,考虑到可能为空的日期:
const begin: Date | null | undefined = // ...
const end: Date | null | undefined = // ...
const defaultDate: Date = new Date();
let min: Date;
let max: Date;
if (!begin || !end) {
min = (begin || end || defaultDate);
max = (begin || end || defaultDate);
} else if (begin > end) {
min = end;
max = begin;
} else {
min = begin;
max = end;
}
我想要强类型代码。当我应用类似问题的解决方案时 - Min/Max of dates in an array? - 我收到错误
TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.
我的代码
const min: Date = Math.min(begin as Date, (end || defaultDate) as Date);
const max: Date = Math.max(begin as Date, (end || defaultDate) as Date);
begin as Date
部分有下划线。
在 Typescript 中查找 min/max 日期的正确方法是什么?
您可以在打字稿中像这样比较日期:
const begin: Date = new Date();
const end: Date = new Date();
const min: Date = begin < end ? begin : end;
const max: Date = begin > end ? begin : end;
您遇到的问题是 Math.min
returns 一个数字。
假设您有一个数组,您将通过获取其 getTime()
来映射日期部分,然后将其传递给 Math.min
,当您取回它时,再次将其转换为日期。
const result:number[] = array.map((item)=>new Date(item.date).getTime());
console.log(new Date(Math.min(...result)));
感谢@OliverRadini 提供示例代码!
我自己的解决方案,考虑到可能为空的日期:
const begin: Date | null | undefined = // ...
const end: Date | null | undefined = // ...
const defaultDate: Date = new Date();
let min: Date;
let max: Date;
if (!begin || !end) {
min = (begin || end || defaultDate);
max = (begin || end || defaultDate);
} else if (begin > end) {
min = end;
max = begin;
} else {
min = begin;
max = end;
}