4

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.

웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91

2 Answers2

4

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

Community
  • 1
  • 1
Orangepill
  • 24,500
  • 3
  • 42
  • 63
1

Try this:

function dateFormat($date, $wanted_format){

    //Zend date
    $zend_date = new Zend_Date();
    $zend_date->set($date, "YYYY-mm-dd");
    //validator
    $validation_date = new Zend_Validate_Date();
    if($validation_date->isValid($zend_date->get('YYYY-mm-dd'))){
        return $zend_date->get($wanted_format);
    }else {
        return "";
    }
}

It will still deals with "YYYY-MM-DD H:i:s" format. You'll get a valid date result at format $wanted_format, only if the date is valid.

NicoDeug
  • 87
  • 7
  • I cannot hardcode the format as 'YYYY-mm-dd' because sometimes the value will be in date formt and sometimes it will be in datetime format.So i cant predefine the format and set it.But thanks for the help @NicoDeug. – 웃웃웃웃웃 May 28 '13 at 10:34