Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

javascript - 使用正则表达式格式化日期(Using Regular Expression to Format Date)

I am trying to ensure the date is in YYYY-MM-DD with the following code:(我正在尝试使用以下代码确保日期在YYYY-MM-DD中:)

var exp = d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]); for(i=0; i<array.length; i++) if(!exp.test(array[i].value) //do something What i have is currently not working, the contents of my if statement are not executing, which leads me to believe either my if statement is set up wrong or my regular expression is wrong, I am stuck on it and cannot figure it out(我目前所拥有的无法正常工作,如果if语句的内容未执行,这使我相信我的if语句设置错误或我的正则表达式错误,我被卡住了,无法弄清楚)   ask by Anna translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your regex will allow invalid dates.(您的正则表达式将允许使用无效日期。)

Here is how to test(这是如何测试) const isDate = dString => { const [yyyy, mm, dd] = dString.split("-"); let d = new Date(yyyy, mm - 1, dd, 15, 0, 0, 0); // handling DST return d.getFullYear() === +yyyy && // casting to number d.getMonth() === mm - 1 && d.getDate() === +dd; } const arr = ["2019-01-01", "2019-02-29"] arr.forEach(dString => console.log(isDate(dString)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...