phpdatedatetimezend-frameworkzend-date

Check valid date in zend framework


I am using zend framework 1.12.0 and i have a value fetching from database to be validated. That is if its a date value then i have to change the format into YYYY-MM-DD to MM/DD/YYYY.Else i keep the value as ''.I am using the following code

    $validator = new Zend_Validate_Date();
    if(trim($value)=='0000-00-00' || $validator->isValid(trim($value))){
         if($validator->isValid(trim($value))){
               $utilObj     =   new Utilityclass();
               $arrayReturn[$key]   =   $utilObj->getDateMdy($value,"/");
          }
          else{
               $arrayReturn[$key]       =   '';
          }
     }

My problem is that the date value may be in YYYY-MM-DD or YYYY-MM-DD H:i:s format.So when its YYYY-MM-DD i am getting the correct output.If its YYYY-MM-DD H:i:s its not converting the format.So how to check a value is a valid date if its in YYYY-MM-DD or YYYY-MM-DD H:i:s format using zend.


Solution

  • The problem is the Zend_Validate_Date doesn't correctly deal with timestamps. One option would be to normalize the $value by passing it through date and strtotime to trim off any times.

    $value = date("Y-m-d", strtotime($value));
    

    this will make the date always be

    YYYY-MM-DD 
    

    Another would be to create your own Timestamp validator

    the only requirment is to implement the isValid, and getMessages method to fulfill the interface of which Zend_Validate_Date has a serviceable implementation. This will remove the restrictions on what the input date format is but I think that is kinda the goal. If you only wanted to allow a couple of different formats that could be easily implemented into this as well.

    class My_Validate_Datetime extends Zend_Validate_Date{
         public function isValid($value){
             // if strtotime can't understand a date it returns 0 which is falsey
             if (strtotime($value)){
                 return true;
             }
             $this->_error(Zend_Validate_Date::INVALID_DATE);
             return false; 
         }
    }
    

    See also this part of the ZF docs or this stack overflow question