dougekui1518
2017-06-22 05:32
浏览 59
已采纳

如何区分日期格式为dd / mm / yy或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. I have used the following patterns with preg_match(), but they do not work.

'^\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?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试访问给定日期值的格式。 我需要检查格式是否在 dd / mm / yy dd / mm / yyyy 中。 我在 preg_match()中使用了以下模式,但它们不起作用。

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

有人可以帮我找到正确的模式吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doupai8533 2017-06-22 05:37
    已采纳

    Problems:

    1. This $ should be in end instead of ^. $ is for end of string.

    2. Don't forget delimiters /.

    Regular expression:

    /^\d{1,2}\/\d{1,2}\/\d{4}$/ for strings like 10/10/1111

    /^\d{1,2}\/\d{1,2}\/\d{2}$/ for strings like 10/10/11

    Try this code snippet here

    已采纳该答案
    打赏 评论
  • doty58493 2017-06-22 06:13

    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.

    PHP checkdate() doc

    打赏 评论

相关推荐 更多相似问题