date-> getTimestamp是否返回该日期的00:00:01?

时间:2013-12-17 21:30:02

标签: php date timestamp unix-timestamp

我正在检查当前时间是否在指定范围内,但是会出现奇怪的行为。

我想知道,也许当我执行$ end_date-> getTimestamp()时,我得到当天第一分钟的时间戳?

在这种情况下,我需要在时间戳上添加(60 * 60 * 24)-1才能获得该$ end_date的23:59:59吗?

private function check_date_in_range($start_date, $end_date)
{
    //Get current time
    $user_ts = time();

    if ($start_date == null && $end_date == null) {
    //if both are null...           

        return 1;
    }
    elseif ($start_date != null && $end_date != null) {
    // if none is null

        //Convert dates to timestamp for comparison
        $start_ts = $start_date->getTimestamp();
        $end_ts = $end_date->getTimestamp();

        // Check that current date is between start & end otherwise return FALSE.
        return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));

2 个答案:

答案 0 :(得分:1)

如果您想测试包容性范围,您确实需要再添加一天:

$now = new DateTime();

$end_date_next = $end_date;
$end_date_next->modify('+1 day');

return $now >= $start_date && $now < $end_date_next;

或者只是在日期部分使用基于字符串的比较:

$now = date('Y-m-d');

return $now >= $start_date->format('Y-m-d') && 
    $now <= $end_date->format('Y-m-d');

答案 1 :(得分:0)

你可以直接比较DateTime对象,所以这样的东西应该有用: -

/**
 * @param DateTime $start_date
 * @param DateTime $end_date
 * @return bool
 */
private function check_date_in_range(\DateTime $start_date, \DateTime $end_date)
{
    if ($start_date == null || $end_date == null) {
        //if either is null bail.
        return false;
    }
    $currDate = new \DateTime();
    $start_date->setTime(0, 0, 0);
    $end_date->setTime(23, 59, 59);

    // Check that current date is between start & end otherwise return FALSE.
    return ($start_date < $currDate && $currDate < $end_date);
}

你也应该意识到,如果你在PHP中使用松散的比较(==),返回1看起来和返回true是一样的。