[英]Need to validate MM/dd/yyyy hh:mm tt in Javascript
I need to validate a date string in a specific format in Javascript. 我需要在Javascript中以特定格式验证日期字符串。
The format is: MM/dd/yyyy hh:mm tt 格式为:MM / dd / yyyy hh:mm tt
I'm having a really hard time trying to find either a date library that will handle it, or a regex function that will do the same. 我很难找到一个可以处理它的日期库或一个正则表达式函数来处理它。
I've tried Date.js, which is close, but has the following problem: 我尝试过Date.js,它很接近,但是有以下问题:
date.parseExact('10/21/2011 06:00 AM', ['MM/dd/yyyy hh:mm tt']); //passes
date.parseExact('10/21/2011 06:00 A', ['MM/dd/yyyy hh:mm tt']); //passes
That second one should not pass. 第二个不应该过去。
Does anyone know of a Regex that could satisfy this need, or perhaps am I using the Date.js library wrong? 有谁知道可以满足此需求的Regex,还是我使用Date.js库错误? Any help would be appreciated, I've been banging my head against the wall for the better part of 2 hours.
任何帮助将不胜感激,我一直将头撞在墙上两个小时。
Do you need to validate that it is an actual date, or just that it follows that exact format? 您是否需要验证它是一个实际日期还是仅遵循该确切格式? If just the format, you can use this regex:
如果只是格式,则可以使用此正则表达式:
/[0-1]\d\/[0-3]\d\/\d{4} [0-1]\d:[0-5]\d [aApP][mM]/
You could use Date.js in combination with the above regex to validate that it is a valid date, and matches your exact format. 您可以将Date.js与上面的正则表达式结合使用,以验证它是一个有效的日期,并与您的确切格式匹配。 Examples:
例子:
01/01/9999 01:00 AM - matches
12/31/9999 01:59 PM - matches
99/99/9999 99:99 AM - no match (day/month out of range)
12/31/9999 99:59 PM - no match (hours out of range)
01/01/9999 99:99 A - no match (no match on A)
Full JS example: 完整的JS示例:
var re = /[0-1]\d\/[0-3]\d\/\d{4} [0-1]\d:[0-5]\d [AP][M]/; // [aApP][mM] for case insensitive AM/PM
var date = '10/21/2011 06:00 AM';
if (re.test(date) && date.parseExact(date, ['MM/dd/yyyy hh:mm tt']){
// date is exact format and valid
}
更严格的正则表达式:
/[01]\d\/[0-3]\d\/\d{4} [01]\d:[0-5]\d [AP]M/
Try this regular expression for the format dd/MM/yyyy hh:mm tt 尝试使用以下正则表达式,格式为dd / MM / yyyy hh:mm tt
"[0-3][0-9]\/[0-1][0-9]\/[0-9]{4} [0-1][0-9]:[0-5][0-9] [paPA][Mm]"
the above expression works as the below formats 上面的表达式按以下格式工作
01/12/9999 01:00 AM - matches
12/31/9999 01:59 PM - no match
39/19/9999 01:59 PM - matches
39/19/9999 99:99 PM - no match (time out of range)
12/31/9999 99:59 PM - no match (hours out of range)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.