加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Doctrine:获取和设置字段值时更改日期格式

发布时间:2020-12-13 17:03:55 所属栏目:PHP教程 来源:网络整理
导读:我希望能够使用我自己的日期格式(dd / mm / yyyy)而不是教条(yyyy-mm-dd)来获取和设置日期.我找到了一种为每个日期字段指定getter和setter的方法,但我想以更方便的方式进行操作(每个表中每个日期字段的1个setter 1 getter很多) class Curs extends BaseCurs
我希望能够使用我自己的日期格式(dd / mm / yyyy)而不是教条(yyyy-mm-dd)来获取和设置日期.我找到了一种为每个日期字段指定getter和setter的方法,但我想以更方便的方式进行操作(每个表中每个日期字段的1个setter 1 getter很多)

class Curs extends BaseCurs {
    private function fechaDesdeEsp($fecha){
        $fecha = new DateTime($fecha);
        return $fecha->format('Y-m-d');
    }
    private function fechaDesdeIso($fecha){
        $fecha = new DateTime($fecha);
        return $fecha->format('d/m/Y');
    }
    public function setFechainici($fecha_inici) {
        return $this->_set('fecha_inici',$this->fechaDesdeEsp($fecha_inici));
    }
    public function getFechainici() {
        return $this->fechaDesdeIso($this->_get('fecha_inici'));
    }

}

希望您找到解决方案,先谢谢

解决方法

我发现这对我来说是最好的解决方案:

/// models/DateFormatBehaior.php
class DateFormatListener extends Doctrine_Record_Listener{

    public function preInsert(Doctrine_event $Event){
        $this->_prepare_date($Event);
    }

    public function preUpdate(Doctrine_event $Event){
        $this->_prepare_date($Event);
    }

    // Private stuff
    private function _prepare_date(Doctrine_event $Event){
        $Model = $Event->getInvoker();
        foreach($Model->getTable()->getColumns() as $FieldName=>$Field){
            if($Field['type']=='timestamp'){
                if(preg_match("/([0-9]{2})/([0-9]{2})/([0-9]{4})/",$Model[$FieldName],$Matches)){
                    $Model->$FieldName = sprintf("%s-%s-%s 00:00:00",$Matches[3],$Matches[2],$Matches[1]); // YYYY-DD-MM HH:MM:SS
                }
            }
        }
    }

}
class DateFormatTemplate extends Doctrine_Template{

    public function setTableDefinition(){

        $this->addListener(new DateFormatListener);
    }

}

然后,每个具有时间戳字段的模型:

/// models/MyModel.php
abstract class MyModel extends Doctrine_Record{

    public function setTableDefinition(){
        // [...]
    }
     public function setUp(){
        parent::setUp();
        $this->actAs("DateFormatTemplate");
        // [...]
     }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读