How best to convert CakePHP date picker form data to a PHP DateTime object?

后端 未结 2 1882
长发绾君心
长发绾君心 2021-01-03 11:25

I\'m doing this in app/views/mymodel/add.ctp:

input(\'Mymodel.mydatefield\'); ?>

And then, in

相关标签:
2条回答
  • 2021-01-03 11:47

    I know this is an old question, but in case anyone else comes looking for an answer: CakePHP's generic Model class has a method, ::deconstruct(), that is used to handle this necessary logic internally. You can use it like this:

    $stringDate = $this->MyModel->deconstruct('fieldname', $arrayDate)
    
    0 讨论(0)
  • 2021-01-03 11:56

    You could write a Helper that takes in $this->data['Mymodel']['mydatefiled'] as a parameter, assumes that year/month/day are in the array, and parse accordingly:

    <?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);
        }
    }
    ?>
    

    Or something like that. I think the DateTime object was added in...PHP 5.2? CakePHP 1.x is targeted at PHP 4 compatibility, so I don't think there's any "CakePHP way" to do it, at least not for 1.x.

    0 讨论(0)
提交回复
热议问题