CakePHP视图变量为datetime而不是string

时间:2012-12-13 19:35:52

标签: string cakephp variables datetime

在我的AppController beforeFilter中我将用户数据保存到变量中以供在我的视图中使用。我需要获取作为日期时间的last_login字段,然后使用dateformat函数显示我想要的日期但是cakephp将此变量作为字符串输出,有没有办法将putput作为表的格式? (日期时间)。

        // Set user variables for each page load
        $id = $this->Auth->user('id');
        // Set $id
        $user_data = $this->User->findById($id);
        // Set User Last Login
        $user_lastlogin = $user_data['User']['last_login'];
        $this->set('lastLogin', $user_lastlogin);

查看

<?php echo date_format($lastLogin, 'F jS \at h:i:s A'); ?>

错误

Warning (2): date_format() expects parameter 1 to be DateTime, string given

1 个答案:

答案 0 :(得分:0)

首先你的代码很乱。试试这个:

$this->User->id = $this->Auth->user('id');
$this->set('lastLogin', $this->User->field('last_login'));

Cake有a class日期和时间。

echo CakeTime::niceShort($lastLogin);

通常,您应该在视图中对数据进行字符串处理,如果您需要对数据执行其他操作,则将其作为控制器或模型的一部分将对您的应用程序产生负面影响。