简体   繁体   English

如何从月份过滤今天

[英]How to filter today from month

I have two functions:我有两个功能:

filterToday(documents) {
      return documents.filter((document) => {
        return (
          new Date(document.date).getDate() === new Date().getDate() &&
          new Date(document.date).getMonth() === new Date().getMonth() &&
          new Date(document.date).getFullYear() === new Date().getFullYear()
        );
      });
    }, 

and

filterThisMonth(documents) {
      return documents.filter((document) => {
        return (
          new Date(document.date).getMonth() === new Date().getMonth() &&
          new Date(document.date).getFullYear() === new Date().getFullYear()
        );
      });
    },

I want to filter today from this month using the function that I created to find today.我想从本月开始使用今天创建的 function 进行过滤。 How can I do that in most efficient way?我怎样才能以最有效的方式做到这一点?

You should create functions that test/match a specific date with a specific document and the use those in your filter calls.您应该创建测试/匹配特定日期与特定文档的函数,并在过滤器调用中使用这些函数。

For the testing functions you can use .toLocaleDateString which supports formatting option, and create the format you want to compare for each scenario.对于测试功能,您可以使用支持格式化选项的.toLocaleDateString ,并为每个场景创建要比较的格式。

something like就像是

 function matchDate(document, date) { const documentDate = new Date(document.date); const options = { year: 'numeric', month: '2-digit', day: '2-digit' }; return date.toLocaleDateString('en-US', options) === documentDate.toLocaleDateString('en-US', options); } function matchYearMonth(document, date) { const documentDate = new Date(document.date); const options = { year: 'numeric', month: '2-digit' }; return date.toLocaleDateString('en-US', options) === documentDate.toLocaleDateString('en-US', options); } filterToday(documents) { const today = new Date(); return documents.filter(document => { return matchToday(document, today) }); } filterThisMonth(documents) { const today = new Date(); return documents.filter((document) => { return matchYearMonth(document, today) &&,matchToday(document; today) }), },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM