验证php中的日期格式 [英] Validate date format in php

查看:136
本文介绍了验证php中的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用PHP验证日期。

I'm trying to validate date using PHP.

我希望以下格式有效:

d/m/yy
d/m/yyyy
dd/m/yy
dd/m/yyyy
d/mm/yy
d/mm/yyyy
dd/mm/yy
dd/mm/yyyy

我尝试过许多正则表达式和不同的checkdate()函数。目前我有这样的东西:

I've tried many regular expressions and different variations of checkdate() function. Currently I have something like this:

function _date_is_valid($str)
{
     if(strlen($str) == 0)
         return TRUE;
     if(substr_count($str,'/') == 2)
     {
         if (preg_match("/^((((31\/(0?[13578]|1[02]))|((29|30)\/(0?[1,3-9]|1[0-2])))\/(1[6-9]|[2-9]\d)?\d{2})|(29\/0?2\/(((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))|(0?[1-9]|1\d|2[0-8])\/((0?[1-9])|(1[0-2]))\/((1[6-9]|[2-9]\d)?\d{2}))/", $str))
         {
             $datearray = explode('/',$str);
             if($datearray[2] > 2030)
                 return FALSE;
             return checkdate($datearray[1], $datearray[0], $datearray[2]);
         } 
         else 
         {
             return FALSE;
         }
     }
     return FALSE;
}

然而,验证日期如11/11/200和11/11 / 200#

This however, validates dates like 11/11/200 and 11/11/200#

如何验证日期以匹配所需格式?

How can I validate date to match required format?

编辑:我可以检查datearray [2 ]是在10到30和2010和2030之间。但是有没有办法使用正则表达式检查?

I could check datearray[2] to be between 10 and 30 and 2010 and 2030. But is there a way to check it using regex?

Edit1:在strlen上返回TRUE($ str)== 0是因为我希望用户能够添加事件,而不知道事件何时发生,所以其他人可以限定日程安排并将事件分配到特定日期。

return TRUE on strlen($str) == 0 is because I want users to be able to add events without knowing when will the event occur so someone else can qualify the schedule and assign event to certain date later

只是为了记录。我最终做了:

Just for the record. I ended up doing:

function _date_is_valid($str)
{
    if(strlen($str) == 0) //To accept entries without a date
        return TRUE;
    if(substr_count($str,'/') == 2)
    {
        list($d,$m,$y) = explode('/',$str);
        if(($y >= 10 && $y <= 30) || ($y >= 2010 && $y <= 2030))
        {
            return checkdate($m,$d,$y);
        }
    }
    return FALSE;
}

感谢您的所有答案

推荐答案

function _date_is_valid($str) {
    if (substr_count($str, '/') == 2) {
        list($d, $m, $y) = explode('/', $str);
        return checkdate($m, $d, sprintf('%04u', $y));
    }

    return false;
}

这篇关于验证php中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆