在模型或控制器中使用date_format?

时间:2017-11-30 20:06:56

标签: php

我已经以这种格式从数据库中检索日期和时间:

2017-11-25 21:08:48

在使用MVC之前我做的是:

$date = date_create($row['article_date']);
$article_date = date_format($date, "d F Y - h:ia");
echo $article_date;

我不确定如何使用MVC来做到这一点。

我的模特:

public function getPosts() {

        $this->db->query("SELECT `id`, `title`, `article`, `article_date`, `slug` FROM `news`");
        $results = $this->db->resultSet();
        return $results;
    }

控制器:

public function index() {

        $posts = $this->postModel->getPosts();

        $data = [

            'posts' => $posts
        ];

        $this->view('posts/index', $data);
    }

然后在视图中我会:

<?php foreach ($data['posts'] as $post){  ?>
  // some html here
<?php echo $post->article_date; ?>

我不能在没有首先使用date_create的情况下在$ post-&gt; article_date上使用date_format。但我只是不确定在哪里使用date_create,即:你会在传递给视图之前在模型或控制器中做到这一点吗?

1 个答案:

答案 0 :(得分:1)

理想情况您不会这样做,而是在视图中执行此操作:

<?php foreach($data['posts'] as $post){ ?>
  // Some HTML here
<?php
    $date = date_create($post->article_date);
    $article_date = date_format($date, "d F Y - h:ia");
    echo $article_date;
  } // Remember to close the foreach!
?>

然而,请注意您根本不需要使用 date_create() ,只需使用 {{3与 date() 结合使用

echo date('d F Y - h:ia', strtotime($post->article_date));

希望这有帮助! :)