3

過去のタイムスタンプを保持する DateTime オブジェクトがあります。

この DateTime がたとえば 48Hours より古いかどうかを確認したいと思います。

それらを最もよく比較するにはどうすればよいですか?

よろしく

編集:こんにちは、

助けてくれてありがとう。ヘルパー メソッドを次に示します。命名の提案はありますか?

    protected function checkTemporalValidity(UserInterface $user, $hours)
{
    $confirmationRequestedAt = $user->getConfirmationTokenRequestedAt();
    $confirmationExpiredAt = new \DateTime('-48hours');

    $timeDifference = $confirmationRequestedAt->diff($confirmationExpiredAt);

    if ($timeDifference->hours >  $hours) {
        return false;
    }

    return true;
}
4

4 に答える 4

4
$a = new DateTime();
$b = new DateTime('-3days');

$diff = $a->diff($b);

if ($diff->days >= 2) {
  echo 'At least 2 days old';
}

「テスト」目的で $a と $b を使用しました。実際の日差を返すメンバ変数を持つDateTime::diffDateIntervalオブジェクトを返します。days

于 2012-04-17T19:16:23.537 に答える
3

ここを見たいと思うかもしれません: PHP 5.2.8で2つのDateTimeオブジェクトを比較するにはどうすればよいですか?

したがって、最も簡単な解決策は、おそらくDateTimeNOW -48Hours の日付を持つ別のオブジェクトを作成し、それと比較することです。

于 2012-04-17T19:13:50.650 に答える
0

何日も働きたくない人へ…

DateTime::getTimestamp()メソッドを使用して UNIX タイムスタンプを取得できます。UNIX のタイムスタンプは秒単位なので、扱いやすいです。したがって、次のことができます。

$now = new DateTime();
$nowInSeconds = $now->getTimestamp();

$confirmationRequestedAtInSeconds = $confirmationRequestedAt->getTimestamp();

$expired = $now > $confirmationRequestedAtInSeconds + 48 * 60 * 60;

$expiredtrue時間切れの場合は

于 2015-03-27T14:34:42.040 に答える