如何最好地将CakePHP日期选择器表单数据转换为PHP DateTime对象?

时间:2010-05-04 10:09:21

标签: php datetime cakephp html-form

我在app/views/mymodel/add.ctp中执行此操作:

<?php echo $form->input('Mymodel.mydatefield'); ?>

然后,在app/controllers/mymodel_controller.php

function add() {
    # ... (if we have some submitted data)
    $datestring = $this->data['Mymodel']['mydatefield']['year'] . '-' .
                  $this->data['Mymodel']['mydatefield']['month'] . '-' .
                  $this->data['Mymodel']['mydatefield']['day'];
    $mydatefield = DateTime::createFromFormat('Y-m-d', $datestring);
}

绝对已经成为更好的方法 - 我还没有找到CakePHP的方式......

我想做的是:

function add() {
    # ... (if we have some submitted data)       
    $mydatefield = $this->data['Mymodel']['mydatefiled']; # obviously doesn't work
}

2 个答案:

答案 0 :(得分:6)

我知道这是一个老问题,但是如果有其他人来寻找答案:CakePHP的通用Model类有一个方法::deconstruct(),用于在内部处理这个必要的逻辑。您可以像这样使用它:

$stringDate = $this->MyModel->deconstruct('fieldname', $arrayDate)

答案 1 :(得分:4)

你可以编写一个Helper,它接受$this->data['Mymodel']['mydatefiled']作为参数,假设年/月/日在数组中,并相应地解析:

<?php
/* /app/views/helpers/date.php */
class DateHelper extends AppHelper {
    function ParseDateTime($dateField) {
         $datestring = $dateField['year'] . '-' .$dateField['month'] . '-' . $dateField['day'];
         return DateTime::createFromFormat('Y-m-d', $datestring);
    }
}
?>

或类似的东西。我认为DateTime对象是在... PHP 5.2中添加的? CakePHP 1.x的目标是兼容PHP 4,所以我认为没有任何“CakePHP方式”可以做到这一点,至少不是1.x。