phpで、x日前の日付を計算して出力する(1日前、1週間前、1ヶ月前、1年前など)

  • 2021年1月1日
  • 2021年1月1日
  • 技術
  • 0件

現在時刻を起点にして、x日前を計算します。計算の方法は、strtotimeを用いて実装してみます。
strtotimeは、Unixタイムスタンプを取得したり、指定した日時のUnixタイムスタンプを取得できる関数です。
参考URL: https://www.php.net/manual/ja/function.strtotime.php

現在時刻から、x日前の日付を計算する

  • 1秒前
echo date("Y-m-d H:i:s", strtotime("-1 second"));
  • 1分前
echo date("Y-m-d H:i:s", strtotime("-1 minute"));
  • 1時間前
echo date("Y-m-d H:i:s", strtotime("-1 hour"));
  • 1日前
echo date("Y-m-d H:i:s", strtotime("-1 day"));
  • 1週間前
echo date("Y-m-d H:i:s", strtotime("-1 week"));
  • 1ヶ月前
echo date("Y-m-d H:i:s", strtotime("-1 month"));
  • 1年前
echo date("Y-m-d H:i:s", strtotime("-1 year"));

指定日時から、x日前の日付を計算する

2020年12月10日の0時を基準に算出してみます。

  • 1秒前
$targetTime = strtotime('2020-12-10 00:00:00');
echo date('Y-m-d H:i:s', strtotime('-1 second', $targetTime));
  • 1分前
$targetTime = strtotime('2020-12-10 00:00:00');
echo date('Y-m-d H:i:s', strtotime('-1 minute', $targetTime));
  • 1時間前
$targetTime = strtotime('2020-12-10 00:00:00');
echo date('Y-m-d H:i:s', strtotime('-1 hour', $targetTime));
  • 1日前
$targetTime = strtotime('2020-12-10 00:00:00');
echo date('Y-m-d H:i:s', strtotime('-1 day', $targetTime));
  • 1週間前
$targetTime = strtotime('2020-12-10 00:00:00');
echo date('Y-m-d H:i:s', strtotime('-1 week', $targetTime));
  • 1ヶ月前
$targetTime = strtotime('2020-12-10 00:00:00');
echo date('Y-m-d H:i:s', strtotime('-1 month', $targetTime));
  • 1年前
$targetTime = strtotime('2020-12-10 00:00:00');
echo date('Y-m-d H:i:s', strtotime('-1 year', $targetTime));