简体   繁体   English

使用正则表达式格式化日期

[英]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 语句设置错误或正则表达式错误,我被困在它上面,无法弄清楚

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)))

I don't check your regexp, but you should put it between / and / - however for date validation regexp are not good tool - eg case 2019-02-29 is invalid... But you can use it for initial format checking eg我不检查你的正则表达式,但你应该把它放在//之间 - 但是对于日期验证正则表达式不是好工具 - 例如案例2019-02-29是无效的......但你可以使用它进行初始格式检查,例如

 let dateString = "2019-05-14"; let [d,year,month,day]= dateString.match(/(\\d{4})-(\\d{2})-(\\d{2})/)||[] if(d) { // here make deeper validation console.log({year,month,day}) } else { console.log('invalid'); }

You are not declaring your regex correctly.您没有正确声明您的正则表达式。 you need to use /regex/ .你需要使用/regex/ Also, you are testing if your string doesn't match, you might want to make sure that's what you really want.此外,您正在测试您的字符串是否不匹配,您可能想要确保这是您真正想要的。

 var exp = /\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])/; let dateString = "2019-05-40"; if(!exp.test(dateString)) { console.log('not matching'); }

as you mentioned you want date format yyyy-mm-dd you can use bellow regex正如你提到的你想要日期格式yyyy-mm-dd你可以使用波纹管regex

/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/

 var exp = /([12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]))/; let yourDate= "2018-09-26"; if(exp.test(yourDate)) { console.log('Date Formated!'); }

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

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