웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

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.

Upvotes: 4

Views: 3902

Answers (2)

NicoDeug
NicoDeug

Reputation: 87

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.

Upvotes: 1

Orangepill
Orangepill

Reputation: 24645

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

Upvotes: 4

Related Questions