检查 JS 中的日期是否是 3 年前或更早

时间:2021-05-18 21:42:32

标签: javascript typescript

所以我想弄清楚如何在 Typescript 中比较两个日期。我有用户输入的日期:

const oldestDateString = this.address[0].since + '-01';
const oldestDate = new Date(oldestDateString);

以及过去三年(36 个月)的日期:

const threeYearsAgo = new Date().setMonth(new Date().getMonth() - 36);

所以我将这些比较如下:

if (oldestDate >= threeYearsAgo) {
      // Do Something
    }

但我在比较时出错:

Operator '<' cannot be applied to types 'Date' and 'number'.

我不明白的是为什么其中一个是数字,当然它们都应该是日期?有什么办法可以比较这两者或以匹配的格式输出它们?它不一定是打字稿解决方案,我什至不介意使用 vanilla JS。

我只是不想使用 momentJS,因为这个特定的功能在某些 iPhone 上似乎不起作用。

旧的momentJS脚本供参考:

const oldestDate = this.address[0].since + '-01';
    const months = moment().diff(moment(oldestDate), 'month', true);
    if (months >= 36) {
      return true;
    } else {
      return false;
    }

2 个答案:

答案 0 :(得分:0)

setMonth 返回一个数字,而不是一个日期。 TS对此很挑剔。比较您调用该 set 函数的日期。

const threeYearsAgo = new Date();
threeYearsAgo.setMonth(new Date().getMonth() - 36);

答案 1 :(得分:0)

这是因为您没有在 threeYearsAgo 中保存日期,而是保存了 setMonth 的返回值。

Date.setMonth Docs

<块引用>

返回值
UTC 时间 1970 年 1 月 1 日 00:00:00 与更新日期之间的毫秒数。

所以你想要

const threeYearsAgo = new Date();
threeYearsAgo.setMonth(new Date().getMonth() - 36)