检查字符串是否与日期匹配?

时间:2019-09-24 13:20:55

标签: javascript node.js typescript search filtering

如果我们有一个用户输入11/25/2014的文本搜索字段,并且有一个日期数组:

var dates = [ new Date(2014, 11, 25), new Date(2014, 11, 24) ];

我们应该如何检查输入的字符串是否与任何日期匹配?

我假设首先会看到它是否实际上是一个有效的日期,因为用户可能输入了foo,而new Date('foo')是无效的日期。

在这之后的includes中有一些像我们对Javascript Date API的字符串所做的一样?

5 个答案:

答案 0 :(得分:2)

您可以使用日期函数格式化日期,并构造所需的格式并将其与输入日期进行比较,并使用findIndex在数组内查找格式化日期的索引:

const input = "11/25/2014";

var dates = [new Date(2014, 11, 25), new Date(2014, 11, 24)];

const exists = str => dates.findIndex(date => {
  const day = date.getDate();
  const monthIndex = date.getMonth();
  const year = date.getFullYear();
  
  return `${monthIndex}/${day}/${year}` === str;
}) > -1 ? true : false;

console.log( exists(input) )

答案 1 :(得分:1)

是的,您需要验证输入日期实际上是一个有效日期,之后您可以检查输入日期的时间戳是否与数组中的某些日期匹配,这可以为您提供帮助

const isValidDate = (inputDate, dates) => {
    const now = new Date(inputDate);
    if (isNaN(now)) {
        throw new Error(`${inputDate} is not a valid date`);
        // or return false instead
    }
    // this will return the first date that matches with the input date
    return dates.some(d => d.getTime() === now.getTime());
}

请记住,您实际上需要验证输入日期的格式,因此,如果日期必须保持dd / mm / YYYY,则必须验证输入日期是否保持该格式。

答案 2 :(得分:0)

这实际上取决于您期望他们的输入保持一致的程度。如果您总是要获得一个类似'DD / MM / YYYY'的日期且没有变化,那么您处在一个合适的位置并且可以轻松完成一些工作。

const userDate = new Date(inputText);
const dates = [ new Date(2014, 11, 25), new Date(2014, 11, 24) ];
const hasMatch = dates.some(d => d.getTime() === userDate.getTime());

答案 3 :(得分:0)

您需要比较要比较的日期的毫秒数。另外请记住,月份是从0开始的,因此您的清单实际上是12月。

const input = '12/25/2014';
const test = new Date(input).getTime();
return !isNaN(test) && [new Date(2014, 11, 25), new Date(2014, 11, 26)]
  .map(d => d.getTime())
  .includes(test)

要注意的一件事是取决于输入,浏览器在使用new Date(str)时解析哪种格式非常不一致,因此,如果要涵盖更多输入格式,请使用类似momentjs

答案 4 :(得分:0)

Stackblitz

const input = "11/25/2014";
let result = [];

if (!isNaN(new Date(input).getTime())) {
  result = dates.filter(date=> {
    const day = date.getDate();
    const monthIndex = date.getMonth();
    const year = date.getFullYear();
    const dateString = `${monthIndex}/${day}/${year}`;
    return dateString.includes(input);
  });
}


console.log("The dates that match are: ", result);
console.log("Two dates match: ", result.length == 2);