怎么做这个倒计时

时间:2012-02-13 15:06:14

标签: php time count

我在数据库中有结束日期

我得到当前日期,我们假设是UTC

class Datecalc
{

    public $year;
    public $month;
    public $day;
    public $hour;
    public $min;
    public $sec;

    function diff($start,$end = false)
    {
        if($start > $end)
        {
            $this->day = 0;
            $this->hour = "00";
            $this->min = "00";
            $this->sec = "00";
            return false;

        }
        if(!$end) { $end = time(); }
        if(!is_numeric($start) || !is_numeric($end)) { return false; }
        $start  = date('Y-m-d H:i:s',$start);
        $end    = date('Y-m-d H:i:s',$end);
        $d_start    = new DateTime($start);
        $d_end      = new DateTime($end);
        $diff = $d_start->diff($d_end);

        $this->year    = $diff->format('%y');
        $this->month    = $diff->format('%m');
        $this->day      = $diff->format('%d');
        $this->hour     = $diff->format('%H');
        $this->min      = $diff->format('%I');
        $this->sec      = $diff->format('%S');

        return true;
    }

}

我使用这个函数来计算时间差,但问题是我不能计算天数到99,而当日期是00:00:00,天数-1,它设置为98和时间23:59:59,在这段代码中一切都很好,但如果天数高于30,它重置为01,我想你明白我想说的,请帮助!!

换句话说,我需要分别计算天数,并且需要将时间绑定到当天

2 个答案:

答案 0 :(得分:1)

您使用的方法永远不会让您获得日期> 30因为30岁以上的任何一天都会被转换为另一个月...

这可能是更好的方法:
http://www.prettyscripts.com/code/php/php-date-difference-in-days

http://www.bizinfosys.com/php/date-difference.html
(简单的谷歌搜索btw ...)

答案 1 :(得分:1)

首先,在检查$ start是否大于$ end之前,你应该检查$ end是否为false。

也就是说,diff方法返回一个DateInterval对象(http://us.php.net/manual/en/class.dateinterval.php),该对象有许多选项,包括日期之间的总天数,以及年,月,日等。你可能想要使用diff方法已经返回的内容,而不是格式函数。

$diff = $d_start->diff($d_end);
echo 'Total days difference: '.$diff->days;
echo 'Year, Month, Days, time difference: '.
$diff->y.' y, '.$diff->m.' m, '.$diff->d.' d, '.$diff->h.' h, '.$diff->i.' m, '.$diff->s.' s, ';
相关问题