如何使用DateTime diff:PHP

时间:2015-05-13 09:16:53

标签: php datetime diff

我在函数中使用DateTime diff函数,为此我需要计算一组日期之间的秒数。我有这个功能:

public function CanBet($bettilltime, $bettilldate, $betsettime, $betsetdate, $amount) {
    $can_bet = true;
    $bettilltime = new DateTime(date("H:i:s", strtotime($bettilltime)));
    $bettilldate = new DateTime(date("Y-m-d", strtotime($bettilldate)));

    $betsettime = new DateTime(date("H:i:s", strtotime("H:i:s", $betsettime)));
    $betsetdate = new DateTime(date("Y-m-d", strtotime("Y-m-d", $betsetdate)));

    $timeDiff = $betsettime->diff($bettilltime);
    return print $timeDiff->s;
    $dateDiff = $betsetdate->diff($bettilldate);
    return print $dateDiff->s;
    if ($this->GetUserBalance() > $amount) {
        if ($timeDiff->s >= 0) {
            if ($dateDiff->s >= 0) {
                $can_bet = true;
            }
            else {
                $can_bet = false;
            }
        }
        else {
            $can_bet = false;
        }
    }
    else {
        $can_bet = false;
    }

    return $can_bet = false;
}

我正在返回$ .... Diff的打印件,以检查它们是否属于某个值,但这些值始终返回0.我尝试使用->d | ->m |->y | ->i | ->s | ->h | ->days(我明白这些值不会返回秒,我用它们来测试)为了从这些中获取打印值,但是,它没有显示0以外的值,我在这里做错了什么?

注意
我在这里设置了最终的返回假,以便让我能够停止使用它的功能,我希望将我的值保持在原样。

1 个答案:

答案 0 :(得分:1)

只需进行简单的DateTime对象比较,这应该可行(并且还可以消除大量虚假的else检查。

public function CanBet($bettilltime, $bettilldate, $betsettime, $betsetdate, $amount) {
    $can_bet = false;

    $bettilltime = new DateTime($bettilltime);
    $bettilldate = new DateTime($bettilldate);

    $betsettime = new DateTime($betsettime);
    $betsetdate = new DateTime($betsetdate); 

    if ($this->GetUserBalance() > $amount) {
        if ($betsettime <= $bettilltime) {
            if ($betsetdate <= $bettilldate) {
                $can_bet = true;
            }
        }
    }

    return $can_bet;
}

public function CanBet($bettilltime, $bettilldate, $betsettime, $betsetdate, $amount) {
    $can_bet = false;

    $bettilltime = new DateTime($bettilldate.' '.$bettilltime);
    $betsettime = new DateTime($betsetdate.' '.$betsettime);

    if ($this->GetUserBalance() > $amount) {
        $can_bet = $betsettime <= $bettilltime;
    }

    return $can_bet;
}
如果没有无意义的日期和时间分割,

将返回完全相同的结果

修改

更简单:

public function CanBet($bettilltime, $bettilldate, $betsettime, $betsetdate, $amount) {
    $bettilltime = new DateTime($bettilldate.' '.$bettilltime);
    $betsettime = new DateTime($betsetdate.' '.$betsettime);

    if ($this->GetUserBalance() > $amount) {
        return $betsettime <= $bettilltime;
    }

    return false;
}