【php】DateTimeとstrtotimeを使って特定の時間だったら日時を戻す方法

一日のリセット時間が夜の毎日0時であれば特に問題ないのですが、特定の時間にリセットする場合比較方法が少し複雑になります。
例えば、毎日3時にリセットされる場合、次のような方法で比較する事ができます。

<?php
// リセット時間指定
$resetTime = '3:00';

// リセット日時をDateTIme型で保持
$resetDate = new \DateTime(
    (new \DateTime())->format('Y-m-d') . ' ' . $resetTime);

// 現在時刻を基準にリセット日時を調整
if(strtotime((new \DateTime())->format('h:i')) <= strtotime($resetTime)) {
    $resetDate->modify('1 days');
}

基準となる日時をDateTimeで日時情報を管理することで、数日後のように簡単に範囲指定をする事ができます。
そのため、範囲指定をする事も簡単に実装できます。

<?php
$times = DB::table('times')
  ->whereRaw(
      '`created_at` BETWEEN '
      . '\'' . (string)$resetDate->format("Y-m-d H:i:s") . '\''
      . ' AND '
      . '\'' . (string)$resetDate->modify('1 days')->format("Y-m-d H:i:s") . '\''
  );

©︎2017-2018 WebSandBag