Validating a valid date in the zend framework

I am using zend framework 1.12.0, and I have a selection from the database for verification. That is, if this is a date value, then I have to change the format in YYYY-MM-DD to MM / DD / YYYY.Else, I save 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 can be in the format YYYY-MM-DD or YYYY-MM-DD H: i: s. Therefore, when its YYYY-MM-DD I get the correct output. If its YYYY- MM-DD H: i: s do not convert the format. So how to check the value, this is a valid date if it is in the format YYYY-MM-DD or YYYY-MM-DD H: i: s using zend.

+4
source share
2 answers

The problem is that Zend_Validate_Date does not handle timestamps correctly. One option would be to normalize the value of $ by passing it through date and strtotime to trim at any time.

 $value = date("Ymd", strtotime($value)); 

it will always make the date

 YYYY-MM-DD 

Another would be to create your own validation

the only requirement is the implementation of the isValid and getMessages method to execute the interface from which Zend_Validate_Date has a working implementation. This will remove restrictions on the format of input dates, but I think this is kind of a goal. If you only wanted to allow a couple of different formats that could be easily implemented in this.

 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 ZF docs or this question.

+4
source

Try the following:

 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 deal with the format "YYYY-MM-DD H: i: s". You will get the correct result in the format $ wanted_format only if the date is valid.

+1
source

Source: https://habr.com/ru/post/1482892/


All Articles