gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:00:19 26 4
gpt4 key购买 nike

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

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

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

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

在那之后是一些 includes,就像我们为 Javascript Date API 处理字符串一样?

最佳答案

您可以使用日期函数格式化日期并构建所需的格式并将其与输入日期进行比较,使用 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) )

关于javascript - 检查字符串是否匹配日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58081288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com