1
0

More than 3 years have passed since last update.

【PHP】timestamp形式の日付時刻をフォーマットして表示したい

Posted at

やりたいこと

現在作成中のアプリで記事投稿日の表示フォーマットを変更したい
image.png

投稿一覧画面のソース抜粋


    <!-- 投稿一覧画面 -->
    <div class="container">
        <div class="contents">
        <?php foreach($posts_arr as $key => $value) :?>

            <div class="card" style="margin-top: 16px;">
                <div class="card-header" style="padding: 0; font-family: serif;">
                    <div class="text-center" style="margin-top: 0.6rem;  line-height: 0rem;">
                        <a><i class="fas fa-fish"></i> <?php echo $posts_arr[$key]['fish_kind']; ?></a>
                    </div>
                    <div class="text-right" style="margin-right: 0.6rem;">
                        <a style="font-size: 0.6rem;">投稿者 <span style="font-size: 0.8rem; font-weight: bold;"><?php echo $posts_arr[$key]['nickname']; ?></span>さん</span></a>
                    </div>
                </div>
                <div class="card-main" style="object-fit: contain; margin-bottom: 16px;">
                    <img src="./img/<?php echo $posts_arr[$key]['file_name']; ?>" class="card-img">
                </div>
                <div class="card-body">
                    <p class="card-text" style="margin-bottom: 0.4rem;"><?php echo mb_strimwidth($posts_arr[$key]['angler_comment'], 0, 200, '…', 'UTF-8'); ?></p>
                    <div class="text-right">
                        <a style="font-size: small;">投稿日: <?php echo $posts_arr[$key]['created_at']; ?></a>
                    </div>
                    <div class="text-right">
                        <a href="./posts/show.php?p_id=<?php echo $posts_arr[$key]['id']; ?>" class="card-link" style="font-size: small;">詳細を見る</a>
                    </div>
                </div>
            </div>

        <?php endforeach; ?>
        </div>
    </div>

改修内容

投稿日: 2020-11-05 21:42:08
表示の秒数部分を無くして
投稿日: 2020-11-05 21:42
にしたい

改修方法

 // 日付表示部分
 <div class="text-right">
     <?php $date = new DateTime($posts_arr[$key]['created_at']);?>
     <a style="font-size: small;">投稿日: <?php echo $date->format('Y-m-d H:i'); ?></a>
 </div>

関数一つ通せばできるものかなと考えながら調べている内にdate_format()を発見

しかし、date_format()はそもそもオブジェクトありきの関数だったため
フォーマットする前にオブジェクトを生成してから実行する必要があると知った。
結論、echoの前にtimestamp形式のデータをオブジェクト生成してからフォーマットする流れでできた。



<?php echo date_format($date, 'Y-m-d H:i'); ?>

もちろんechoの部分はこれでもいけますがなるべくオブジェクト指向の記述で書きたいので
前者の方を採用しました。

image.png

や↑ったぜ

参考

PHP公式リファレンス

1
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0