简体   繁体   English

如何区分日期格式为dd / mm / yy或dd / mm / yyyy?

[英]How to differentiate date formats as dd/mm/yy or dd/mm/yyyy?

I'm trying to access the format of a given date value. 我正在尝试访问给定日期值的格式。 I need to check whether the format is in dd/mm/yy or dd/mm/yyyy . 我需要检查格式是dd/mm/yy还是dd/mm/yyyy I have used the following patterns with preg_match() , but they do not work. 我在preg_match()使用了以下模式,但是它们不起作用。

'^\d{1,2}\/\d{1,2}\/\d{4}^'  //  dd/mm/yyyy

'^\d{1,2}\/\d{1,2}\/\d{2}^'  //  dd/mm/yy

Can someone help me to find the correct pattern? 有人可以帮助我找到正确的模式吗?

Problems: 问题:

1. This $ should be in end instead of ^ . 1.$应该在末尾而不是^ $ is for end of string. $是字符串的结尾。

2. Don't forget delimiters / . 2.不要忘记定界符/

Regular expression: 正则表达式:

/^\\d{1,2}\\/\\d{1,2}\\/\\d{4}$/ for strings like 10/10/1111 /^\\d{1,2}\\/\\d{1,2}\\/\\d{4}$/用于类似10/10/1111字符串

/^\\d{1,2}\\/\\d{1,2}\\/\\d{2}$/ for strings like 10/10/11 /^\\d{1,2}\\/\\d{1,2}\\/\\d{2}$/用于类似10/10/11字符串

Try this code snippet here 在此处尝试此代码段

You have an error in the syntax of your regular expression. 正则表达式的语法有误。 In a regex, the start of the pattern is denoted by ^ while the end is by $. 在正则表达式中,模式的开始由^表示,而结束由$表示。

You can use the following to validate the given date format. 您可以使用以下内容验证给定的日期格式。

$date_to_check = "22/06/2017";
$true = preg_match("/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/", $date_to_check);
var_dump($true);

However, you shouldn't be validating a date against a regex expression only. 但是,您不应该只针对正则表达式表达式验证日期。 You need to pass the Year, month, date to the php's checkdate() function to really validate it. 您需要将Year,month,date传递给php的checkdate()函数,以真正对其进行验证。

PHP checkdate() doc PHP checkdate()文件

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

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