【问题标题】:Find min/max of two dates (typed)查找两个日期的最小值/最大值(键入)
【发布时间】:2020-09-19 16:59:48
【问题描述】:

我想要一个强类型代码。当我应用类似问题的解决方案时 - 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 中查找最小/最大日期的正确方法是什么?

【问题讨论】:

  • Math.min()Math.max() 返回一个数字。您不能让它们返回带有类型的 Date 对象。
  • @GuyIncognito 我明白了,我明白了。但正确的方法是什么? const min: Date = new Date(Math.min(begin.getDate(), (end || hover).getDate())) ?

标签: typescript date max min


【解决方案1】:

您可以在 typescript 中像这样比较日期:

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 返回一个数字。

【讨论】:

    【解决方案2】:

    假设您有一个数组,您将通过获取其getTime() 映射日期部分,然后将其传递给Math.min,当您取回它时,再次将其转换为日期。

    const result:number[] = array.map((item)=>new Date(item.date).getTime());
    console.log(new Date(Math.min(...result)));

    【讨论】:

      【解决方案3】:

      感谢@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;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-08-29
        • 2021-09-23
        • 1970-01-01
        • 2020-06-20
        • 1970-01-01
        • 2012-04-18
        • 1970-01-01
        • 1970-01-01
        • 2013-11-15
        相关资源
        最近更新 更多