[PHP] strtotime関数で日時指定し、要素の表示・非表示を切り替える方法
PHPの strtotime関数を使い、日時を指定して要素の表示・非表示を切り替える方法をご紹介します。
特定の期間中だけバナーを表示したい場合などに便利です。
strtotime関数とは?
strtotime関数は、人間が理解しやすい形式の日付・時刻の文字列を、UNIXタイムスタンプに変換する関数です。
UNIXタイムスタンプとは、1970年1月1日 00:00:00(UTC)からの経過秒数で日時を表現する仕組みです。
サンプルコード:指定日時以降に要素を非表示にする
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php // 現在のUNIXタイムスタンプを取得 $current_time = time(); // 指定日時(2026年4月20日 16:30)のUNIXタイムスタンプを取得 $target_time = strtotime('2026-04-20 16:30'); // 現在時刻が指定日時以上の場合 if ($current_time >= $target_time) { // .special_bnrクラスを持つ要素を非表示にする echo '<style>.special_bnr { display: none; }</style>'; } ?> <div class="special_bnr"> <a href="/special01/"> <img src="images/bnr01.gif" alt="バナー"> </a> </div> |
サンプルコード:指定日時で表示内容を切り替える
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php $current_time = time(); $target_time = strtotime('2026-04-20 16:30'); if ($current_time < $target_time) { ?> <div class="bnr"> <a href="/special01/"> <img src="images/bnr01.gif" alt="バナー1"> </a> </div> <?php } else { ?> <div class="bnr"> <a href="/special02/"> <img src="images/bnr02.gif" alt="バナー2"> </a> </div> <?php } ?> |
日時指定のサンプル一覧
・今現在
|
1 |
<?php echo date('Y-m-d H:i:s', strtotime('now')); ?> |
・本日
|
1 |
<?php echo date('Y-m-d', strtotime('today')); ?> |
・日時指定
|
1 |
<?php echo date('Y-m-d H:i:s', strtotime('2026-04-20 16:30')); ?> |
・7日後
|
1 |
<?php echo date('Y-m-d', strtotime('+7 days')); ?> |
・1か月後
|
1 |
<?php echo date('Y-m-d', strtotime('+1 month')); ?> |
※strtotime()は日時を「UNIXタイムスタンプ(数値)」に変換する関数のため、そのままでは人間が読める形式になりません。date()関数と組み合わせて使用するのが一般的です。
→ 出力結果
![MARKLEAPS[マークリープス]](https://markleaps.com/blog/wp-content/themes/mkl/images/00_logo.png)