javascript - JavaScript 过滤器助手中的精确字符串匹配未返回 true

标签 javascript date date-fns

我正在使用过滤器助手来创建与今天的日期匹配的新项目数组。我已经确认这两个比较都是长度为 10 的字符串,但在过滤器中进行比较时,它们没有被识别为匹配项。

我知道它与新的 Date() 方法有关,因为当我针对日期字符串测试它时,第一次比较有效,而新的 Date 方法则不然。

if(chosenDate === 'today') {
      // this does not work even though both values are equal
      const scheduled = this.props.scheduled.filter(event => event.scheduled_at.substring(0, 10) === new Date(), 'yyyy-MM-dd');

      // this works
      const scheduled = this.props.scheduled.filter(event => event.scheduled_at.substring(0, 10) === '2019-11-14');

      // this does not work
      const scheduled = this.props.scheduled.filter(event => '2019-11-14' === new Date(), 'yyyy-MM-dd');
      console.log(scheduled)
    }

    console.log(this.props.scheduled[0].scheduled_at.substring(0, 10));
    console.log(dateFnsFormat(new Date(), 'yyyy-MM-dd'));

为什么新的日期字符串比较不相等?

最佳答案

看来你的意思是

const scheduled = this.props.scheduled.filter(event =>
  event.scheduled_at.substring(0, 10) === dateFnsFormat(new Date(), 'yyyy-MM-dd')
);

但是写了

const scheduled = this.props.scheduled.filter(event =>
  event.scheduled_at.substring(0, 10) === new Date()
, 'yyyy-MM-dd'
);

关于javascript - JavaScript 过滤器助手中的精确字符串匹配未返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58868180/

相关文章:

javascript - 当我按下按钮时如何知道调用哪个函数?

javascript - Passport - 无法读取属性 'isAuthenticated'

javascript - Angular指令不获取父级设置的值

php - MySQL:在选择查询中操作日期和字符串

javascript - 是否有任何 JavaScript 方法可以复制 Oracle 的 ADD_MONTH() 功能

javascript - 类型错误 : format is not a function in date-fns

javascript - jQuery removeAttr ('type' ) 不起作用

Linux 日期格式 hh-mm-ss

typescript - 更新 ESLint 出现以下错误 : imported multiple times import/no-duplicates

javascript - 接收字符串并使用 date-fns 验证它是否是有效日期